diffusers 0.32.2__py3-none-any.whl → 0.33.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- diffusers/__init__.py +186 -3
- diffusers/configuration_utils.py +40 -12
- diffusers/dependency_versions_table.py +9 -2
- diffusers/hooks/__init__.py +9 -0
- diffusers/hooks/faster_cache.py +653 -0
- diffusers/hooks/group_offloading.py +793 -0
- diffusers/hooks/hooks.py +236 -0
- diffusers/hooks/layerwise_casting.py +245 -0
- diffusers/hooks/pyramid_attention_broadcast.py +311 -0
- diffusers/loaders/__init__.py +6 -0
- diffusers/loaders/ip_adapter.py +38 -30
- diffusers/loaders/lora_base.py +121 -86
- diffusers/loaders/lora_conversion_utils.py +504 -44
- diffusers/loaders/lora_pipeline.py +1769 -181
- diffusers/loaders/peft.py +167 -57
- diffusers/loaders/single_file.py +17 -2
- diffusers/loaders/single_file_model.py +53 -5
- diffusers/loaders/single_file_utils.py +646 -72
- diffusers/loaders/textual_inversion.py +9 -9
- diffusers/loaders/transformer_flux.py +8 -9
- diffusers/loaders/transformer_sd3.py +120 -39
- diffusers/loaders/unet.py +20 -7
- diffusers/models/__init__.py +22 -0
- diffusers/models/activations.py +9 -9
- diffusers/models/attention.py +0 -1
- diffusers/models/attention_processor.py +163 -25
- diffusers/models/auto_model.py +169 -0
- diffusers/models/autoencoders/__init__.py +2 -0
- diffusers/models/autoencoders/autoencoder_asym_kl.py +2 -0
- diffusers/models/autoencoders/autoencoder_dc.py +106 -4
- diffusers/models/autoencoders/autoencoder_kl.py +0 -4
- diffusers/models/autoencoders/autoencoder_kl_allegro.py +5 -23
- diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +17 -55
- diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py +17 -97
- diffusers/models/autoencoders/autoencoder_kl_ltx.py +326 -107
- diffusers/models/autoencoders/autoencoder_kl_magvit.py +1094 -0
- diffusers/models/autoencoders/autoencoder_kl_mochi.py +21 -56
- diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +11 -42
- diffusers/models/autoencoders/autoencoder_kl_wan.py +855 -0
- diffusers/models/autoencoders/autoencoder_oobleck.py +1 -0
- diffusers/models/autoencoders/autoencoder_tiny.py +0 -4
- diffusers/models/autoencoders/consistency_decoder_vae.py +3 -1
- diffusers/models/autoencoders/vae.py +31 -141
- diffusers/models/autoencoders/vq_model.py +3 -0
- diffusers/models/cache_utils.py +108 -0
- diffusers/models/controlnets/__init__.py +1 -0
- diffusers/models/controlnets/controlnet.py +3 -8
- diffusers/models/controlnets/controlnet_flux.py +14 -42
- diffusers/models/controlnets/controlnet_sd3.py +58 -34
- diffusers/models/controlnets/controlnet_sparsectrl.py +4 -7
- diffusers/models/controlnets/controlnet_union.py +27 -18
- diffusers/models/controlnets/controlnet_xs.py +7 -46
- diffusers/models/controlnets/multicontrolnet_union.py +196 -0
- diffusers/models/embeddings.py +18 -7
- diffusers/models/model_loading_utils.py +122 -80
- diffusers/models/modeling_flax_pytorch_utils.py +1 -1
- diffusers/models/modeling_flax_utils.py +1 -1
- diffusers/models/modeling_pytorch_flax_utils.py +1 -1
- diffusers/models/modeling_utils.py +617 -272
- diffusers/models/normalization.py +67 -14
- diffusers/models/resnet.py +1 -1
- diffusers/models/transformers/__init__.py +6 -0
- diffusers/models/transformers/auraflow_transformer_2d.py +9 -35
- diffusers/models/transformers/cogvideox_transformer_3d.py +13 -24
- diffusers/models/transformers/consisid_transformer_3d.py +789 -0
- diffusers/models/transformers/dit_transformer_2d.py +5 -19
- diffusers/models/transformers/hunyuan_transformer_2d.py +4 -3
- diffusers/models/transformers/latte_transformer_3d.py +20 -15
- diffusers/models/transformers/lumina_nextdit2d.py +3 -1
- diffusers/models/transformers/pixart_transformer_2d.py +4 -19
- diffusers/models/transformers/prior_transformer.py +5 -1
- diffusers/models/transformers/sana_transformer.py +144 -40
- diffusers/models/transformers/stable_audio_transformer.py +5 -20
- diffusers/models/transformers/transformer_2d.py +7 -22
- diffusers/models/transformers/transformer_allegro.py +9 -17
- diffusers/models/transformers/transformer_cogview3plus.py +6 -17
- diffusers/models/transformers/transformer_cogview4.py +462 -0
- diffusers/models/transformers/transformer_easyanimate.py +527 -0
- diffusers/models/transformers/transformer_flux.py +68 -110
- diffusers/models/transformers/transformer_hunyuan_video.py +404 -46
- diffusers/models/transformers/transformer_ltx.py +53 -35
- diffusers/models/transformers/transformer_lumina2.py +548 -0
- diffusers/models/transformers/transformer_mochi.py +6 -17
- diffusers/models/transformers/transformer_omnigen.py +469 -0
- diffusers/models/transformers/transformer_sd3.py +56 -86
- diffusers/models/transformers/transformer_temporal.py +5 -11
- diffusers/models/transformers/transformer_wan.py +469 -0
- diffusers/models/unets/unet_1d.py +3 -1
- diffusers/models/unets/unet_2d.py +21 -20
- diffusers/models/unets/unet_2d_blocks.py +19 -243
- diffusers/models/unets/unet_2d_condition.py +4 -6
- diffusers/models/unets/unet_3d_blocks.py +14 -127
- diffusers/models/unets/unet_3d_condition.py +8 -12
- diffusers/models/unets/unet_i2vgen_xl.py +5 -13
- diffusers/models/unets/unet_kandinsky3.py +0 -4
- diffusers/models/unets/unet_motion_model.py +20 -114
- diffusers/models/unets/unet_spatio_temporal_condition.py +7 -8
- diffusers/models/unets/unet_stable_cascade.py +8 -35
- diffusers/models/unets/uvit_2d.py +1 -4
- diffusers/optimization.py +2 -2
- diffusers/pipelines/__init__.py +57 -8
- diffusers/pipelines/allegro/pipeline_allegro.py +22 -2
- diffusers/pipelines/amused/pipeline_amused.py +15 -2
- diffusers/pipelines/amused/pipeline_amused_img2img.py +15 -2
- diffusers/pipelines/amused/pipeline_amused_inpaint.py +15 -2
- diffusers/pipelines/animatediff/pipeline_animatediff.py +15 -2
- diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +15 -3
- diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +24 -4
- diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +15 -2
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +16 -4
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +16 -4
- diffusers/pipelines/audioldm/pipeline_audioldm.py +13 -2
- diffusers/pipelines/audioldm2/modeling_audioldm2.py +13 -68
- diffusers/pipelines/audioldm2/pipeline_audioldm2.py +39 -9
- diffusers/pipelines/aura_flow/pipeline_aura_flow.py +63 -7
- diffusers/pipelines/auto_pipeline.py +35 -14
- diffusers/pipelines/blip_diffusion/blip_image_processing.py +1 -1
- diffusers/pipelines/blip_diffusion/modeling_blip2.py +5 -8
- diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +12 -0
- diffusers/pipelines/cogvideo/pipeline_cogvideox.py +22 -6
- diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +22 -6
- diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +22 -5
- diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +22 -6
- diffusers/pipelines/cogview3/pipeline_cogview3plus.py +12 -4
- diffusers/pipelines/cogview4/__init__.py +49 -0
- diffusers/pipelines/cogview4/pipeline_cogview4.py +684 -0
- diffusers/pipelines/cogview4/pipeline_cogview4_control.py +732 -0
- diffusers/pipelines/cogview4/pipeline_output.py +21 -0
- diffusers/pipelines/consisid/__init__.py +49 -0
- diffusers/pipelines/consisid/consisid_utils.py +357 -0
- diffusers/pipelines/consisid/pipeline_consisid.py +974 -0
- diffusers/pipelines/consisid/pipeline_output.py +20 -0
- diffusers/pipelines/consistency_models/pipeline_consistency_models.py +11 -0
- diffusers/pipelines/controlnet/pipeline_controlnet.py +6 -5
- diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +13 -0
- diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +17 -5
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +31 -12
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +26 -7
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +20 -3
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +22 -3
- diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +26 -25
- diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +224 -109
- diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +25 -29
- diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +7 -4
- diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +3 -5
- diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +121 -10
- diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +122 -11
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +12 -1
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +20 -3
- diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +14 -2
- diffusers/pipelines/ddim/pipeline_ddim.py +14 -1
- diffusers/pipelines/ddpm/pipeline_ddpm.py +15 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if.py +12 -0
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +12 -0
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +14 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +12 -0
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +14 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +14 -1
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +11 -7
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +11 -7
- diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +1 -1
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +10 -6
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_onnx_stable_diffusion_inpaint_legacy.py +2 -2
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +11 -7
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +1 -1
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +1 -1
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +1 -1
- diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +10 -105
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py +1 -1
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +1 -1
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +1 -1
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +1 -1
- diffusers/pipelines/dit/pipeline_dit.py +15 -2
- diffusers/pipelines/easyanimate/__init__.py +52 -0
- diffusers/pipelines/easyanimate/pipeline_easyanimate.py +770 -0
- diffusers/pipelines/easyanimate/pipeline_easyanimate_control.py +994 -0
- diffusers/pipelines/easyanimate/pipeline_easyanimate_inpaint.py +1234 -0
- diffusers/pipelines/easyanimate/pipeline_output.py +20 -0
- diffusers/pipelines/flux/pipeline_flux.py +53 -21
- diffusers/pipelines/flux/pipeline_flux_control.py +9 -12
- diffusers/pipelines/flux/pipeline_flux_control_img2img.py +6 -10
- diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +8 -10
- diffusers/pipelines/flux/pipeline_flux_controlnet.py +185 -13
- diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +8 -10
- diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +16 -16
- diffusers/pipelines/flux/pipeline_flux_fill.py +107 -39
- diffusers/pipelines/flux/pipeline_flux_img2img.py +193 -15
- diffusers/pipelines/flux/pipeline_flux_inpaint.py +199 -19
- diffusers/pipelines/free_noise_utils.py +3 -3
- diffusers/pipelines/hunyuan_video/__init__.py +4 -0
- diffusers/pipelines/hunyuan_video/pipeline_hunyuan_skyreels_image2video.py +804 -0
- diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +90 -23
- diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video_image2video.py +924 -0
- diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +3 -5
- diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +13 -1
- diffusers/pipelines/kandinsky/pipeline_kandinsky.py +12 -0
- diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +1 -1
- diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +12 -0
- diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +13 -1
- diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +12 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +12 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +13 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +12 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +12 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +12 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +12 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +12 -0
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +12 -0
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +12 -0
- diffusers/pipelines/kolors/pipeline_kolors.py +10 -8
- diffusers/pipelines/kolors/pipeline_kolors_img2img.py +6 -4
- diffusers/pipelines/kolors/text_encoder.py +7 -34
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +12 -1
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +13 -1
- diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +14 -13
- diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion_superresolution.py +12 -1
- diffusers/pipelines/latte/pipeline_latte.py +36 -7
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +67 -13
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +60 -15
- diffusers/pipelines/ltx/__init__.py +2 -0
- diffusers/pipelines/ltx/pipeline_ltx.py +25 -13
- diffusers/pipelines/ltx/pipeline_ltx_condition.py +1194 -0
- diffusers/pipelines/ltx/pipeline_ltx_image2video.py +31 -17
- diffusers/pipelines/lumina/__init__.py +2 -2
- diffusers/pipelines/lumina/pipeline_lumina.py +83 -20
- diffusers/pipelines/lumina2/__init__.py +48 -0
- diffusers/pipelines/lumina2/pipeline_lumina2.py +790 -0
- diffusers/pipelines/marigold/__init__.py +2 -0
- diffusers/pipelines/marigold/marigold_image_processing.py +127 -14
- diffusers/pipelines/marigold/pipeline_marigold_depth.py +31 -16
- diffusers/pipelines/marigold/pipeline_marigold_intrinsics.py +721 -0
- diffusers/pipelines/marigold/pipeline_marigold_normals.py +31 -16
- diffusers/pipelines/mochi/pipeline_mochi.py +14 -18
- diffusers/pipelines/musicldm/pipeline_musicldm.py +16 -1
- diffusers/pipelines/omnigen/__init__.py +50 -0
- diffusers/pipelines/omnigen/pipeline_omnigen.py +512 -0
- diffusers/pipelines/omnigen/processor_omnigen.py +327 -0
- diffusers/pipelines/onnx_utils.py +5 -3
- diffusers/pipelines/pag/pag_utils.py +1 -1
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +12 -1
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +15 -4
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +20 -3
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +20 -3
- diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +1 -3
- diffusers/pipelines/pag/pipeline_pag_kolors.py +6 -4
- diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +16 -3
- diffusers/pipelines/pag/pipeline_pag_sana.py +65 -8
- diffusers/pipelines/pag/pipeline_pag_sd.py +23 -7
- diffusers/pipelines/pag/pipeline_pag_sd_3.py +3 -5
- diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +3 -5
- diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +13 -1
- diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +23 -7
- diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +26 -10
- diffusers/pipelines/pag/pipeline_pag_sd_xl.py +12 -4
- diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +7 -3
- diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +10 -6
- diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +13 -3
- diffusers/pipelines/pia/pipeline_pia.py +13 -1
- diffusers/pipelines/pipeline_flax_utils.py +7 -7
- diffusers/pipelines/pipeline_loading_utils.py +193 -83
- diffusers/pipelines/pipeline_utils.py +221 -106
- diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +17 -5
- diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +17 -4
- diffusers/pipelines/sana/__init__.py +2 -0
- diffusers/pipelines/sana/pipeline_sana.py +183 -58
- diffusers/pipelines/sana/pipeline_sana_sprint.py +889 -0
- diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +12 -2
- diffusers/pipelines/shap_e/pipeline_shap_e.py +12 -0
- diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +12 -0
- diffusers/pipelines/shap_e/renderer.py +6 -6
- diffusers/pipelines/stable_audio/pipeline_stable_audio.py +1 -1
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +15 -4
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +12 -8
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +12 -1
- diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +3 -2
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +14 -10
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_img2img.py +3 -3
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_inpaint.py +14 -10
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +2 -2
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +4 -3
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +5 -4
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +2 -2
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +18 -13
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +30 -8
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +24 -10
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +28 -12
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +39 -18
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +17 -6
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +13 -3
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +20 -3
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +14 -2
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +13 -1
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +16 -17
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +136 -18
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +150 -21
- diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +15 -3
- diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +26 -11
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +15 -3
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +22 -4
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +30 -13
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +12 -4
- diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +15 -3
- diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +15 -3
- diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +26 -12
- diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +16 -4
- diffusers/pipelines/stable_diffusion_xl/pipeline_flax_stable_diffusion_xl.py +1 -1
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +12 -4
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +7 -3
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +10 -6
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +11 -4
- diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +13 -2
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +18 -4
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +26 -5
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +13 -1
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +13 -1
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +28 -6
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +26 -4
- diffusers/pipelines/transformers_loading_utils.py +121 -0
- diffusers/pipelines/unclip/pipeline_unclip.py +11 -1
- diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +11 -1
- diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +19 -2
- diffusers/pipelines/wan/__init__.py +51 -0
- diffusers/pipelines/wan/pipeline_output.py +20 -0
- diffusers/pipelines/wan/pipeline_wan.py +595 -0
- diffusers/pipelines/wan/pipeline_wan_i2v.py +724 -0
- diffusers/pipelines/wan/pipeline_wan_video2video.py +727 -0
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +7 -31
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +12 -1
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +12 -1
- diffusers/quantizers/auto.py +5 -1
- diffusers/quantizers/base.py +5 -9
- diffusers/quantizers/bitsandbytes/bnb_quantizer.py +41 -29
- diffusers/quantizers/bitsandbytes/utils.py +30 -20
- diffusers/quantizers/gguf/gguf_quantizer.py +1 -0
- diffusers/quantizers/gguf/utils.py +4 -2
- diffusers/quantizers/quantization_config.py +59 -4
- diffusers/quantizers/quanto/__init__.py +1 -0
- diffusers/quantizers/quanto/quanto_quantizer.py +177 -0
- diffusers/quantizers/quanto/utils.py +60 -0
- diffusers/quantizers/torchao/__init__.py +1 -1
- diffusers/quantizers/torchao/torchao_quantizer.py +47 -2
- diffusers/schedulers/__init__.py +2 -1
- diffusers/schedulers/scheduling_consistency_models.py +1 -2
- diffusers/schedulers/scheduling_ddim_inverse.py +1 -1
- diffusers/schedulers/scheduling_ddpm.py +2 -3
- diffusers/schedulers/scheduling_ddpm_parallel.py +1 -2
- diffusers/schedulers/scheduling_dpmsolver_multistep.py +12 -4
- diffusers/schedulers/scheduling_edm_euler.py +45 -10
- diffusers/schedulers/scheduling_flow_match_euler_discrete.py +116 -28
- diffusers/schedulers/scheduling_flow_match_heun_discrete.py +7 -6
- diffusers/schedulers/scheduling_heun_discrete.py +1 -1
- diffusers/schedulers/scheduling_lcm.py +1 -2
- diffusers/schedulers/scheduling_lms_discrete.py +1 -1
- diffusers/schedulers/scheduling_repaint.py +5 -1
- diffusers/schedulers/scheduling_scm.py +265 -0
- diffusers/schedulers/scheduling_tcd.py +1 -2
- diffusers/schedulers/scheduling_utils.py +2 -1
- diffusers/training_utils.py +14 -7
- diffusers/utils/__init__.py +9 -1
- diffusers/utils/constants.py +13 -1
- diffusers/utils/deprecation_utils.py +1 -1
- diffusers/utils/dummy_bitsandbytes_objects.py +17 -0
- diffusers/utils/dummy_gguf_objects.py +17 -0
- diffusers/utils/dummy_optimum_quanto_objects.py +17 -0
- diffusers/utils/dummy_pt_objects.py +233 -0
- diffusers/utils/dummy_torch_and_transformers_and_opencv_objects.py +17 -0
- diffusers/utils/dummy_torch_and_transformers_objects.py +270 -0
- diffusers/utils/dummy_torchao_objects.py +17 -0
- diffusers/utils/dynamic_modules_utils.py +1 -1
- diffusers/utils/export_utils.py +28 -3
- diffusers/utils/hub_utils.py +52 -102
- diffusers/utils/import_utils.py +121 -221
- diffusers/utils/loading_utils.py +2 -1
- diffusers/utils/logging.py +1 -2
- diffusers/utils/peft_utils.py +6 -14
- diffusers/utils/remote_utils.py +425 -0
- diffusers/utils/source_code_parsing_utils.py +52 -0
- diffusers/utils/state_dict_utils.py +15 -1
- diffusers/utils/testing_utils.py +243 -13
- diffusers/utils/torch_utils.py +10 -0
- diffusers/utils/typing_utils.py +91 -0
- diffusers/video_processor.py +1 -1
- {diffusers-0.32.2.dist-info → diffusers-0.33.1.dist-info}/METADATA +21 -4
- diffusers-0.33.1.dist-info/RECORD +608 -0
- {diffusers-0.32.2.dist-info → diffusers-0.33.1.dist-info}/WHEEL +1 -1
- diffusers-0.32.2.dist-info/RECORD +0 -550
- {diffusers-0.32.2.dist-info → diffusers-0.33.1.dist-info}/LICENSE +0 -0
- {diffusers-0.32.2.dist-info → diffusers-0.33.1.dist-info}/entry_points.txt +0 -0
- {diffusers-0.32.2.dist-info → diffusers-0.33.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1234 @@
|
|
1
|
+
# Copyright 2025 The EasyAnimate team and The HuggingFace Team.
|
2
|
+
# All rights reserved.
|
3
|
+
#
|
4
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5
|
+
# you may not use this file except in compliance with the License.
|
6
|
+
# You may obtain a copy of the License at
|
7
|
+
#
|
8
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9
|
+
#
|
10
|
+
# Unless required by applicable law or agreed to in writing, software
|
11
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13
|
+
# See the License for the specific language governing permissions and
|
14
|
+
# limitations under the License.
|
15
|
+
|
16
|
+
import inspect
|
17
|
+
from typing import Callable, Dict, List, Optional, Union
|
18
|
+
|
19
|
+
import numpy as np
|
20
|
+
import torch
|
21
|
+
import torch.nn.functional as F
|
22
|
+
from PIL import Image
|
23
|
+
from transformers import (
|
24
|
+
BertModel,
|
25
|
+
BertTokenizer,
|
26
|
+
Qwen2Tokenizer,
|
27
|
+
Qwen2VLForConditionalGeneration,
|
28
|
+
)
|
29
|
+
|
30
|
+
from ...callbacks import MultiPipelineCallbacks, PipelineCallback
|
31
|
+
from ...image_processor import VaeImageProcessor
|
32
|
+
from ...models import AutoencoderKLMagvit, EasyAnimateTransformer3DModel
|
33
|
+
from ...pipelines.pipeline_utils import DiffusionPipeline
|
34
|
+
from ...schedulers import FlowMatchEulerDiscreteScheduler
|
35
|
+
from ...utils import is_torch_xla_available, logging, replace_example_docstring
|
36
|
+
from ...utils.torch_utils import randn_tensor
|
37
|
+
from ...video_processor import VideoProcessor
|
38
|
+
from .pipeline_output import EasyAnimatePipelineOutput
|
39
|
+
|
40
|
+
|
41
|
+
if is_torch_xla_available():
|
42
|
+
import torch_xla.core.xla_model as xm
|
43
|
+
|
44
|
+
XLA_AVAILABLE = True
|
45
|
+
else:
|
46
|
+
XLA_AVAILABLE = False
|
47
|
+
|
48
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
49
|
+
|
50
|
+
|
51
|
+
EXAMPLE_DOC_STRING = """
|
52
|
+
Examples:
|
53
|
+
```py
|
54
|
+
>>> import torch
|
55
|
+
>>> from diffusers import EasyAnimateInpaintPipeline
|
56
|
+
>>> from diffusers.pipelines.easyanimate.pipeline_easyanimate_inpaint import get_image_to_video_latent
|
57
|
+
>>> from diffusers.utils import export_to_video, load_image
|
58
|
+
|
59
|
+
>>> pipe = EasyAnimateInpaintPipeline.from_pretrained(
|
60
|
+
... "alibaba-pai/EasyAnimateV5.1-12b-zh-InP-diffusers", torch_dtype=torch.bfloat16
|
61
|
+
... )
|
62
|
+
>>> pipe.to("cuda")
|
63
|
+
|
64
|
+
>>> prompt = "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
|
65
|
+
>>> validation_image_start = load_image(
|
66
|
+
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
|
67
|
+
... )
|
68
|
+
|
69
|
+
>>> validation_image_end = None
|
70
|
+
>>> sample_size = (448, 576)
|
71
|
+
>>> num_frames = 49
|
72
|
+
>>> input_video, input_video_mask = get_image_to_video_latent(
|
73
|
+
... [validation_image_start], validation_image_end, num_frames, sample_size
|
74
|
+
... )
|
75
|
+
|
76
|
+
>>> video = pipe(
|
77
|
+
... prompt,
|
78
|
+
... num_frames=num_frames,
|
79
|
+
... negative_prompt="Twisted body, limb deformities, text subtitles, comics, stillness, ugliness, errors, garbled text.",
|
80
|
+
... height=sample_size[0],
|
81
|
+
... width=sample_size[1],
|
82
|
+
... video=input_video,
|
83
|
+
... mask_video=input_video_mask,
|
84
|
+
... )
|
85
|
+
>>> export_to_video(video.frames[0], "output.mp4", fps=8)
|
86
|
+
```
|
87
|
+
"""
|
88
|
+
|
89
|
+
|
90
|
+
def preprocess_image(image, sample_size):
|
91
|
+
"""
|
92
|
+
Preprocess a single image (PIL.Image, numpy.ndarray, or torch.Tensor) to a resized tensor.
|
93
|
+
"""
|
94
|
+
if isinstance(image, torch.Tensor):
|
95
|
+
# If input is a tensor, assume it's in CHW format and resize using interpolation
|
96
|
+
image = torch.nn.functional.interpolate(
|
97
|
+
image.unsqueeze(0), size=sample_size, mode="bilinear", align_corners=False
|
98
|
+
).squeeze(0)
|
99
|
+
elif isinstance(image, Image.Image):
|
100
|
+
# If input is a PIL image, resize and convert to numpy array
|
101
|
+
image = image.resize((sample_size[1], sample_size[0]))
|
102
|
+
image = np.array(image)
|
103
|
+
elif isinstance(image, np.ndarray):
|
104
|
+
# If input is a numpy array, resize using PIL
|
105
|
+
image = Image.fromarray(image).resize((sample_size[1], sample_size[0]))
|
106
|
+
image = np.array(image)
|
107
|
+
else:
|
108
|
+
raise ValueError("Unsupported input type. Expected PIL.Image, numpy.ndarray, or torch.Tensor.")
|
109
|
+
|
110
|
+
# Convert to tensor if not already
|
111
|
+
if not isinstance(image, torch.Tensor):
|
112
|
+
image = torch.from_numpy(image).permute(2, 0, 1).float() / 255.0 # HWC -> CHW, normalize to [0, 1]
|
113
|
+
|
114
|
+
return image
|
115
|
+
|
116
|
+
|
117
|
+
def get_image_to_video_latent(validation_image_start, validation_image_end, num_frames, sample_size):
|
118
|
+
"""
|
119
|
+
Generate latent representations for video from start and end images. Inputs can be PIL.Image, numpy.ndarray, or
|
120
|
+
torch.Tensor.
|
121
|
+
"""
|
122
|
+
input_video = None
|
123
|
+
input_video_mask = None
|
124
|
+
|
125
|
+
if validation_image_start is not None:
|
126
|
+
# Preprocess the starting image(s)
|
127
|
+
if isinstance(validation_image_start, list):
|
128
|
+
image_start = [preprocess_image(img, sample_size) for img in validation_image_start]
|
129
|
+
else:
|
130
|
+
image_start = preprocess_image(validation_image_start, sample_size)
|
131
|
+
|
132
|
+
# Create video tensor from the starting image(s)
|
133
|
+
if isinstance(image_start, list):
|
134
|
+
start_video = torch.cat(
|
135
|
+
[img.unsqueeze(1).unsqueeze(0) for img in image_start],
|
136
|
+
dim=2,
|
137
|
+
)
|
138
|
+
input_video = torch.tile(start_video[:, :, :1], [1, 1, num_frames, 1, 1])
|
139
|
+
input_video[:, :, : len(image_start)] = start_video
|
140
|
+
else:
|
141
|
+
input_video = torch.tile(
|
142
|
+
image_start.unsqueeze(1).unsqueeze(0),
|
143
|
+
[1, 1, num_frames, 1, 1],
|
144
|
+
)
|
145
|
+
|
146
|
+
# Normalize input video (already normalized in preprocess_image)
|
147
|
+
|
148
|
+
# Create mask for the input video
|
149
|
+
input_video_mask = torch.zeros_like(input_video[:, :1])
|
150
|
+
if isinstance(image_start, list):
|
151
|
+
input_video_mask[:, :, len(image_start) :] = 255
|
152
|
+
else:
|
153
|
+
input_video_mask[:, :, 1:] = 255
|
154
|
+
|
155
|
+
# Handle ending image(s) if provided
|
156
|
+
if validation_image_end is not None:
|
157
|
+
if isinstance(validation_image_end, list):
|
158
|
+
image_end = [preprocess_image(img, sample_size) for img in validation_image_end]
|
159
|
+
end_video = torch.cat(
|
160
|
+
[img.unsqueeze(1).unsqueeze(0) for img in image_end],
|
161
|
+
dim=2,
|
162
|
+
)
|
163
|
+
input_video[:, :, -len(end_video) :] = end_video
|
164
|
+
input_video_mask[:, :, -len(image_end) :] = 0
|
165
|
+
else:
|
166
|
+
image_end = preprocess_image(validation_image_end, sample_size)
|
167
|
+
input_video[:, :, -1:] = image_end.unsqueeze(1).unsqueeze(0)
|
168
|
+
input_video_mask[:, :, -1:] = 0
|
169
|
+
|
170
|
+
elif validation_image_start is None:
|
171
|
+
# If no starting image is provided, initialize empty tensors
|
172
|
+
input_video = torch.zeros([1, 3, num_frames, sample_size[0], sample_size[1]])
|
173
|
+
input_video_mask = torch.ones([1, 1, num_frames, sample_size[0], sample_size[1]]) * 255
|
174
|
+
|
175
|
+
return input_video, input_video_mask
|
176
|
+
|
177
|
+
|
178
|
+
# Similar to diffusers.pipelines.hunyuandit.pipeline_hunyuandit.get_resize_crop_region_for_grid
|
179
|
+
def get_resize_crop_region_for_grid(src, tgt_width, tgt_height):
|
180
|
+
tw = tgt_width
|
181
|
+
th = tgt_height
|
182
|
+
h, w = src
|
183
|
+
r = h / w
|
184
|
+
if r > (th / tw):
|
185
|
+
resize_height = th
|
186
|
+
resize_width = int(round(th / h * w))
|
187
|
+
else:
|
188
|
+
resize_width = tw
|
189
|
+
resize_height = int(round(tw / w * h))
|
190
|
+
|
191
|
+
crop_top = int(round((th - resize_height) / 2.0))
|
192
|
+
crop_left = int(round((tw - resize_width) / 2.0))
|
193
|
+
|
194
|
+
return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)
|
195
|
+
|
196
|
+
|
197
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
|
198
|
+
def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
|
199
|
+
r"""
|
200
|
+
Rescales `noise_cfg` tensor based on `guidance_rescale` to improve image quality and fix overexposure. Based on
|
201
|
+
Section 3.4 from [Common Diffusion Noise Schedules and Sample Steps are
|
202
|
+
Flawed](https://arxiv.org/pdf/2305.08891.pdf).
|
203
|
+
|
204
|
+
Args:
|
205
|
+
noise_cfg (`torch.Tensor`):
|
206
|
+
The predicted noise tensor for the guided diffusion process.
|
207
|
+
noise_pred_text (`torch.Tensor`):
|
208
|
+
The predicted noise tensor for the text-guided diffusion process.
|
209
|
+
guidance_rescale (`float`, *optional*, defaults to 0.0):
|
210
|
+
A rescale factor applied to the noise predictions.
|
211
|
+
|
212
|
+
Returns:
|
213
|
+
noise_cfg (`torch.Tensor`): The rescaled noise prediction tensor.
|
214
|
+
"""
|
215
|
+
std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
|
216
|
+
std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
|
217
|
+
# rescale the results from guidance (fixes overexposure)
|
218
|
+
noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
|
219
|
+
# mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
|
220
|
+
noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
|
221
|
+
return noise_cfg
|
222
|
+
|
223
|
+
|
224
|
+
# Resize mask information in magvit
|
225
|
+
def resize_mask(mask, latent, process_first_frame_only=True):
|
226
|
+
latent_size = latent.size()
|
227
|
+
|
228
|
+
if process_first_frame_only:
|
229
|
+
target_size = list(latent_size[2:])
|
230
|
+
target_size[0] = 1
|
231
|
+
first_frame_resized = F.interpolate(
|
232
|
+
mask[:, :, 0:1, :, :], size=target_size, mode="trilinear", align_corners=False
|
233
|
+
)
|
234
|
+
|
235
|
+
target_size = list(latent_size[2:])
|
236
|
+
target_size[0] = target_size[0] - 1
|
237
|
+
if target_size[0] != 0:
|
238
|
+
remaining_frames_resized = F.interpolate(
|
239
|
+
mask[:, :, 1:, :, :], size=target_size, mode="trilinear", align_corners=False
|
240
|
+
)
|
241
|
+
resized_mask = torch.cat([first_frame_resized, remaining_frames_resized], dim=2)
|
242
|
+
else:
|
243
|
+
resized_mask = first_frame_resized
|
244
|
+
else:
|
245
|
+
target_size = list(latent_size[2:])
|
246
|
+
resized_mask = F.interpolate(mask, size=target_size, mode="trilinear", align_corners=False)
|
247
|
+
return resized_mask
|
248
|
+
|
249
|
+
|
250
|
+
## Add noise to reference video
|
251
|
+
def add_noise_to_reference_video(image, ratio=None, generator=None):
|
252
|
+
if ratio is None:
|
253
|
+
sigma = torch.normal(mean=-3.0, std=0.5, size=(image.shape[0],)).to(image.device)
|
254
|
+
sigma = torch.exp(sigma).to(image.dtype)
|
255
|
+
else:
|
256
|
+
sigma = torch.ones((image.shape[0],)).to(image.device, image.dtype) * ratio
|
257
|
+
|
258
|
+
if generator is not None:
|
259
|
+
image_noise = (
|
260
|
+
torch.randn(image.size(), generator=generator, dtype=image.dtype, device=image.device)
|
261
|
+
* sigma[:, None, None, None, None]
|
262
|
+
)
|
263
|
+
else:
|
264
|
+
image_noise = torch.randn_like(image) * sigma[:, None, None, None, None]
|
265
|
+
image_noise = torch.where(image == -1, torch.zeros_like(image), image_noise)
|
266
|
+
image = image + image_noise
|
267
|
+
return image
|
268
|
+
|
269
|
+
|
270
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
271
|
+
def retrieve_timesteps(
|
272
|
+
scheduler,
|
273
|
+
num_inference_steps: Optional[int] = None,
|
274
|
+
device: Optional[Union[str, torch.device]] = None,
|
275
|
+
timesteps: Optional[List[int]] = None,
|
276
|
+
sigmas: Optional[List[float]] = None,
|
277
|
+
**kwargs,
|
278
|
+
):
|
279
|
+
r"""
|
280
|
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
281
|
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
282
|
+
|
283
|
+
Args:
|
284
|
+
scheduler (`SchedulerMixin`):
|
285
|
+
The scheduler to get timesteps from.
|
286
|
+
num_inference_steps (`int`):
|
287
|
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
288
|
+
must be `None`.
|
289
|
+
device (`str` or `torch.device`, *optional*):
|
290
|
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
291
|
+
timesteps (`List[int]`, *optional*):
|
292
|
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
293
|
+
`num_inference_steps` and `sigmas` must be `None`.
|
294
|
+
sigmas (`List[float]`, *optional*):
|
295
|
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
296
|
+
`num_inference_steps` and `timesteps` must be `None`.
|
297
|
+
|
298
|
+
Returns:
|
299
|
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
300
|
+
second element is the number of inference steps.
|
301
|
+
"""
|
302
|
+
if timesteps is not None and sigmas is not None:
|
303
|
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
304
|
+
if timesteps is not None:
|
305
|
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
306
|
+
if not accepts_timesteps:
|
307
|
+
raise ValueError(
|
308
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
309
|
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
310
|
+
)
|
311
|
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
312
|
+
timesteps = scheduler.timesteps
|
313
|
+
num_inference_steps = len(timesteps)
|
314
|
+
elif sigmas is not None:
|
315
|
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
316
|
+
if not accept_sigmas:
|
317
|
+
raise ValueError(
|
318
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
319
|
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
320
|
+
)
|
321
|
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
322
|
+
timesteps = scheduler.timesteps
|
323
|
+
num_inference_steps = len(timesteps)
|
324
|
+
else:
|
325
|
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
326
|
+
timesteps = scheduler.timesteps
|
327
|
+
return timesteps, num_inference_steps
|
328
|
+
|
329
|
+
|
330
|
+
class EasyAnimateInpaintPipeline(DiffusionPipeline):
|
331
|
+
r"""
|
332
|
+
Pipeline for text-to-video generation using EasyAnimate.
|
333
|
+
|
334
|
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
335
|
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
336
|
+
|
337
|
+
EasyAnimate uses one text encoder [qwen2 vl](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct) in V5.1.
|
338
|
+
|
339
|
+
Args:
|
340
|
+
vae ([`AutoencoderKLMagvit`]):
|
341
|
+
Variational Auto-Encoder (VAE) Model to encode and decode video to and from latent representations.
|
342
|
+
text_encoder (Optional[`~transformers.Qwen2VLForConditionalGeneration`, `~transformers.BertModel`]):
|
343
|
+
EasyAnimate uses [qwen2 vl](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct) in V5.1.
|
344
|
+
tokenizer (Optional[`~transformers.Qwen2Tokenizer`, `~transformers.BertTokenizer`]):
|
345
|
+
A `Qwen2Tokenizer` or `BertTokenizer` to tokenize text.
|
346
|
+
transformer ([`EasyAnimateTransformer3DModel`]):
|
347
|
+
The EasyAnimate model designed by EasyAnimate Team.
|
348
|
+
scheduler ([`FlowMatchEulerDiscreteScheduler`]):
|
349
|
+
A scheduler to be used in combination with EasyAnimate to denoise the encoded image latents.
|
350
|
+
"""
|
351
|
+
|
352
|
+
model_cpu_offload_seq = "text_encoder->transformer->vae"
|
353
|
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
354
|
+
|
355
|
+
def __init__(
|
356
|
+
self,
|
357
|
+
vae: AutoencoderKLMagvit,
|
358
|
+
text_encoder: Union[Qwen2VLForConditionalGeneration, BertModel],
|
359
|
+
tokenizer: Union[Qwen2Tokenizer, BertTokenizer],
|
360
|
+
transformer: EasyAnimateTransformer3DModel,
|
361
|
+
scheduler: FlowMatchEulerDiscreteScheduler,
|
362
|
+
):
|
363
|
+
super().__init__()
|
364
|
+
|
365
|
+
self.register_modules(
|
366
|
+
vae=vae,
|
367
|
+
text_encoder=text_encoder,
|
368
|
+
tokenizer=tokenizer,
|
369
|
+
transformer=transformer,
|
370
|
+
scheduler=scheduler,
|
371
|
+
)
|
372
|
+
|
373
|
+
self.enable_text_attention_mask = (
|
374
|
+
self.transformer.config.enable_text_attention_mask
|
375
|
+
if getattr(self, "transformer", None) is not None
|
376
|
+
else True
|
377
|
+
)
|
378
|
+
self.vae_spatial_compression_ratio = (
|
379
|
+
self.vae.spatial_compression_ratio if getattr(self, "vae", None) is not None else 8
|
380
|
+
)
|
381
|
+
self.vae_temporal_compression_ratio = (
|
382
|
+
self.vae.temporal_compression_ratio if getattr(self, "vae", None) is not None else 4
|
383
|
+
)
|
384
|
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_spatial_compression_ratio)
|
385
|
+
self.mask_processor = VaeImageProcessor(
|
386
|
+
vae_scale_factor=self.vae_spatial_compression_ratio,
|
387
|
+
do_normalize=False,
|
388
|
+
do_binarize=True,
|
389
|
+
do_convert_grayscale=True,
|
390
|
+
)
|
391
|
+
self.video_processor = VideoProcessor(vae_scale_factor=self.vae_spatial_compression_ratio)
|
392
|
+
|
393
|
+
# Copied from diffusers.pipelines.easyanimate.pipeline_easyanimate.EasyAnimatePipeline.encode_prompt
|
394
|
+
def encode_prompt(
|
395
|
+
self,
|
396
|
+
prompt: Union[str, List[str]],
|
397
|
+
num_images_per_prompt: int = 1,
|
398
|
+
do_classifier_free_guidance: bool = True,
|
399
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
400
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
401
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
402
|
+
prompt_attention_mask: Optional[torch.Tensor] = None,
|
403
|
+
negative_prompt_attention_mask: Optional[torch.Tensor] = None,
|
404
|
+
device: Optional[torch.device] = None,
|
405
|
+
dtype: Optional[torch.dtype] = None,
|
406
|
+
max_sequence_length: int = 256,
|
407
|
+
):
|
408
|
+
r"""
|
409
|
+
Encodes the prompt into text encoder hidden states.
|
410
|
+
|
411
|
+
Args:
|
412
|
+
prompt (`str` or `List[str]`, *optional*):
|
413
|
+
prompt to be encoded
|
414
|
+
device: (`torch.device`):
|
415
|
+
torch device
|
416
|
+
dtype (`torch.dtype`):
|
417
|
+
torch dtype
|
418
|
+
num_images_per_prompt (`int`):
|
419
|
+
number of images that should be generated per prompt
|
420
|
+
do_classifier_free_guidance (`bool`):
|
421
|
+
whether to use classifier free guidance or not
|
422
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
423
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
424
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
425
|
+
less than `1`).
|
426
|
+
prompt_embeds (`torch.Tensor`, *optional*):
|
427
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
428
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
429
|
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
430
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
431
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
432
|
+
argument.
|
433
|
+
prompt_attention_mask (`torch.Tensor`, *optional*):
|
434
|
+
Attention mask for the prompt. Required when `prompt_embeds` is passed directly.
|
435
|
+
negative_prompt_attention_mask (`torch.Tensor`, *optional*):
|
436
|
+
Attention mask for the negative prompt. Required when `negative_prompt_embeds` is passed directly.
|
437
|
+
max_sequence_length (`int`, *optional*): maximum sequence length to use for the prompt.
|
438
|
+
"""
|
439
|
+
dtype = dtype or self.text_encoder.dtype
|
440
|
+
device = device or self.text_encoder.device
|
441
|
+
|
442
|
+
if prompt is not None and isinstance(prompt, str):
|
443
|
+
batch_size = 1
|
444
|
+
elif prompt is not None and isinstance(prompt, list):
|
445
|
+
batch_size = len(prompt)
|
446
|
+
else:
|
447
|
+
batch_size = prompt_embeds.shape[0]
|
448
|
+
|
449
|
+
if prompt_embeds is None:
|
450
|
+
if isinstance(prompt, str):
|
451
|
+
messages = [
|
452
|
+
{
|
453
|
+
"role": "user",
|
454
|
+
"content": [{"type": "text", "text": prompt}],
|
455
|
+
}
|
456
|
+
]
|
457
|
+
else:
|
458
|
+
messages = [
|
459
|
+
{
|
460
|
+
"role": "user",
|
461
|
+
"content": [{"type": "text", "text": _prompt}],
|
462
|
+
}
|
463
|
+
for _prompt in prompt
|
464
|
+
]
|
465
|
+
text = [
|
466
|
+
self.tokenizer.apply_chat_template([m], tokenize=False, add_generation_prompt=True) for m in messages
|
467
|
+
]
|
468
|
+
|
469
|
+
text_inputs = self.tokenizer(
|
470
|
+
text=text,
|
471
|
+
padding="max_length",
|
472
|
+
max_length=max_sequence_length,
|
473
|
+
truncation=True,
|
474
|
+
return_attention_mask=True,
|
475
|
+
padding_side="right",
|
476
|
+
return_tensors="pt",
|
477
|
+
)
|
478
|
+
text_inputs = text_inputs.to(self.text_encoder.device)
|
479
|
+
|
480
|
+
text_input_ids = text_inputs.input_ids
|
481
|
+
prompt_attention_mask = text_inputs.attention_mask
|
482
|
+
if self.enable_text_attention_mask:
|
483
|
+
# Inference: Generation of the output
|
484
|
+
prompt_embeds = self.text_encoder(
|
485
|
+
input_ids=text_input_ids, attention_mask=prompt_attention_mask, output_hidden_states=True
|
486
|
+
).hidden_states[-2]
|
487
|
+
else:
|
488
|
+
raise ValueError("LLM needs attention_mask")
|
489
|
+
prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)
|
490
|
+
|
491
|
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
492
|
+
|
493
|
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
494
|
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
495
|
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
496
|
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
497
|
+
prompt_attention_mask = prompt_attention_mask.to(device=device)
|
498
|
+
|
499
|
+
# get unconditional embeddings for classifier free guidance
|
500
|
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
501
|
+
if negative_prompt is not None and isinstance(negative_prompt, str):
|
502
|
+
messages = [
|
503
|
+
{
|
504
|
+
"role": "user",
|
505
|
+
"content": [{"type": "text", "text": negative_prompt}],
|
506
|
+
}
|
507
|
+
]
|
508
|
+
else:
|
509
|
+
messages = [
|
510
|
+
{
|
511
|
+
"role": "user",
|
512
|
+
"content": [{"type": "text", "text": _negative_prompt}],
|
513
|
+
}
|
514
|
+
for _negative_prompt in negative_prompt
|
515
|
+
]
|
516
|
+
text = [
|
517
|
+
self.tokenizer.apply_chat_template([m], tokenize=False, add_generation_prompt=True) for m in messages
|
518
|
+
]
|
519
|
+
|
520
|
+
text_inputs = self.tokenizer(
|
521
|
+
text=text,
|
522
|
+
padding="max_length",
|
523
|
+
max_length=max_sequence_length,
|
524
|
+
truncation=True,
|
525
|
+
return_attention_mask=True,
|
526
|
+
padding_side="right",
|
527
|
+
return_tensors="pt",
|
528
|
+
)
|
529
|
+
text_inputs = text_inputs.to(self.text_encoder.device)
|
530
|
+
|
531
|
+
text_input_ids = text_inputs.input_ids
|
532
|
+
negative_prompt_attention_mask = text_inputs.attention_mask
|
533
|
+
if self.enable_text_attention_mask:
|
534
|
+
# Inference: Generation of the output
|
535
|
+
negative_prompt_embeds = self.text_encoder(
|
536
|
+
input_ids=text_input_ids,
|
537
|
+
attention_mask=negative_prompt_attention_mask,
|
538
|
+
output_hidden_states=True,
|
539
|
+
).hidden_states[-2]
|
540
|
+
else:
|
541
|
+
raise ValueError("LLM needs attention_mask")
|
542
|
+
negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(num_images_per_prompt, 1)
|
543
|
+
|
544
|
+
if do_classifier_free_guidance:
|
545
|
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
546
|
+
seq_len = negative_prompt_embeds.shape[1]
|
547
|
+
|
548
|
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
|
549
|
+
|
550
|
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
551
|
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
552
|
+
negative_prompt_attention_mask = negative_prompt_attention_mask.to(device=device)
|
553
|
+
|
554
|
+
return prompt_embeds, negative_prompt_embeds, prompt_attention_mask, negative_prompt_attention_mask
|
555
|
+
|
556
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
557
|
+
def prepare_extra_step_kwargs(self, generator, eta):
|
558
|
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
559
|
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
560
|
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
561
|
+
# and should be between [0, 1]
|
562
|
+
|
563
|
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
564
|
+
extra_step_kwargs = {}
|
565
|
+
if accepts_eta:
|
566
|
+
extra_step_kwargs["eta"] = eta
|
567
|
+
|
568
|
+
# check if the scheduler accepts generator
|
569
|
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
570
|
+
if accepts_generator:
|
571
|
+
extra_step_kwargs["generator"] = generator
|
572
|
+
return extra_step_kwargs
|
573
|
+
|
574
|
+
def check_inputs(
|
575
|
+
self,
|
576
|
+
prompt,
|
577
|
+
height,
|
578
|
+
width,
|
579
|
+
negative_prompt=None,
|
580
|
+
prompt_embeds=None,
|
581
|
+
negative_prompt_embeds=None,
|
582
|
+
prompt_attention_mask=None,
|
583
|
+
negative_prompt_attention_mask=None,
|
584
|
+
callback_on_step_end_tensor_inputs=None,
|
585
|
+
):
|
586
|
+
if height % 16 != 0 or width % 16 != 0:
|
587
|
+
raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
|
588
|
+
|
589
|
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
590
|
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
591
|
+
):
|
592
|
+
raise ValueError(
|
593
|
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
594
|
+
)
|
595
|
+
|
596
|
+
if prompt is not None and prompt_embeds is not None:
|
597
|
+
raise ValueError(
|
598
|
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
599
|
+
" only forward one of the two."
|
600
|
+
)
|
601
|
+
elif prompt is None and prompt_embeds is None:
|
602
|
+
raise ValueError(
|
603
|
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
604
|
+
)
|
605
|
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
606
|
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
607
|
+
|
608
|
+
if prompt_embeds is not None and prompt_attention_mask is None:
|
609
|
+
raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.")
|
610
|
+
|
611
|
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
612
|
+
raise ValueError(
|
613
|
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
614
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
615
|
+
)
|
616
|
+
|
617
|
+
if negative_prompt_embeds is not None and negative_prompt_attention_mask is None:
|
618
|
+
raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.")
|
619
|
+
|
620
|
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
621
|
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
622
|
+
raise ValueError(
|
623
|
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
624
|
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
625
|
+
f" {negative_prompt_embeds.shape}."
|
626
|
+
)
|
627
|
+
|
628
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps
|
629
|
+
def get_timesteps(self, num_inference_steps, strength, device):
|
630
|
+
# get the original timestep using init_timestep
|
631
|
+
init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
|
632
|
+
|
633
|
+
t_start = max(num_inference_steps - init_timestep, 0)
|
634
|
+
timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
|
635
|
+
if hasattr(self.scheduler, "set_begin_index"):
|
636
|
+
self.scheduler.set_begin_index(t_start * self.scheduler.order)
|
637
|
+
|
638
|
+
return timesteps, num_inference_steps - t_start
|
639
|
+
|
640
|
+
def prepare_mask_latents(
|
641
|
+
self,
|
642
|
+
mask,
|
643
|
+
masked_image,
|
644
|
+
batch_size,
|
645
|
+
height,
|
646
|
+
width,
|
647
|
+
dtype,
|
648
|
+
device,
|
649
|
+
generator,
|
650
|
+
do_classifier_free_guidance,
|
651
|
+
noise_aug_strength,
|
652
|
+
):
|
653
|
+
# resize the mask to latents shape as we concatenate the mask to the latents
|
654
|
+
# we do that before converting to dtype to avoid breaking in case we're using cpu_offload
|
655
|
+
# and half precision
|
656
|
+
if mask is not None:
|
657
|
+
mask = mask.to(device=device, dtype=dtype)
|
658
|
+
new_mask = []
|
659
|
+
bs = 1
|
660
|
+
for i in range(0, mask.shape[0], bs):
|
661
|
+
mask_bs = mask[i : i + bs]
|
662
|
+
mask_bs = self.vae.encode(mask_bs)[0]
|
663
|
+
mask_bs = mask_bs.mode()
|
664
|
+
new_mask.append(mask_bs)
|
665
|
+
mask = torch.cat(new_mask, dim=0)
|
666
|
+
mask = mask * self.vae.config.scaling_factor
|
667
|
+
|
668
|
+
if masked_image is not None:
|
669
|
+
masked_image = masked_image.to(device=device, dtype=dtype)
|
670
|
+
if self.transformer.config.add_noise_in_inpaint_model:
|
671
|
+
masked_image = add_noise_to_reference_video(
|
672
|
+
masked_image, ratio=noise_aug_strength, generator=generator
|
673
|
+
)
|
674
|
+
new_mask_pixel_values = []
|
675
|
+
bs = 1
|
676
|
+
for i in range(0, masked_image.shape[0], bs):
|
677
|
+
mask_pixel_values_bs = masked_image[i : i + bs]
|
678
|
+
mask_pixel_values_bs = self.vae.encode(mask_pixel_values_bs)[0]
|
679
|
+
mask_pixel_values_bs = mask_pixel_values_bs.mode()
|
680
|
+
new_mask_pixel_values.append(mask_pixel_values_bs)
|
681
|
+
masked_image_latents = torch.cat(new_mask_pixel_values, dim=0)
|
682
|
+
masked_image_latents = masked_image_latents * self.vae.config.scaling_factor
|
683
|
+
|
684
|
+
# aligning device to prevent device errors when concating it with the latent model input
|
685
|
+
masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
|
686
|
+
else:
|
687
|
+
masked_image_latents = None
|
688
|
+
|
689
|
+
return mask, masked_image_latents
|
690
|
+
|
691
|
+
def prepare_latents(
|
692
|
+
self,
|
693
|
+
batch_size,
|
694
|
+
num_channels_latents,
|
695
|
+
height,
|
696
|
+
width,
|
697
|
+
num_frames,
|
698
|
+
dtype,
|
699
|
+
device,
|
700
|
+
generator,
|
701
|
+
latents=None,
|
702
|
+
video=None,
|
703
|
+
timestep=None,
|
704
|
+
is_strength_max=True,
|
705
|
+
return_noise=False,
|
706
|
+
return_video_latents=False,
|
707
|
+
):
|
708
|
+
shape = (
|
709
|
+
batch_size,
|
710
|
+
num_channels_latents,
|
711
|
+
(num_frames - 1) // self.vae_temporal_compression_ratio + 1,
|
712
|
+
height // self.vae_spatial_compression_ratio,
|
713
|
+
width // self.vae_spatial_compression_ratio,
|
714
|
+
)
|
715
|
+
|
716
|
+
if isinstance(generator, list) and len(generator) != batch_size:
|
717
|
+
raise ValueError(
|
718
|
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
719
|
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
720
|
+
)
|
721
|
+
|
722
|
+
if return_video_latents or (latents is None and not is_strength_max):
|
723
|
+
video = video.to(device=device, dtype=dtype)
|
724
|
+
bs = 1
|
725
|
+
new_video = []
|
726
|
+
for i in range(0, video.shape[0], bs):
|
727
|
+
video_bs = video[i : i + bs]
|
728
|
+
video_bs = self.vae.encode(video_bs)[0]
|
729
|
+
video_bs = video_bs.sample()
|
730
|
+
new_video.append(video_bs)
|
731
|
+
video = torch.cat(new_video, dim=0)
|
732
|
+
video = video * self.vae.config.scaling_factor
|
733
|
+
|
734
|
+
video_latents = video.repeat(batch_size // video.shape[0], 1, 1, 1, 1)
|
735
|
+
video_latents = video_latents.to(device=device, dtype=dtype)
|
736
|
+
|
737
|
+
if latents is None:
|
738
|
+
noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
739
|
+
# if strength is 1. then initialise the latents to noise, else initial to image + noise
|
740
|
+
if isinstance(self.scheduler, FlowMatchEulerDiscreteScheduler):
|
741
|
+
latents = noise if is_strength_max else self.scheduler.scale_noise(video_latents, timestep, noise)
|
742
|
+
else:
|
743
|
+
latents = noise if is_strength_max else self.scheduler.add_noise(video_latents, noise, timestep)
|
744
|
+
# if pure noise then scale the initial latents by the Scheduler's init sigma
|
745
|
+
if hasattr(self.scheduler, "init_noise_sigma"):
|
746
|
+
latents = latents * self.scheduler.init_noise_sigma if is_strength_max else latents
|
747
|
+
else:
|
748
|
+
if hasattr(self.scheduler, "init_noise_sigma"):
|
749
|
+
noise = latents.to(device)
|
750
|
+
latents = noise * self.scheduler.init_noise_sigma
|
751
|
+
else:
|
752
|
+
latents = latents.to(device)
|
753
|
+
|
754
|
+
# scale the initial noise by the standard deviation required by the scheduler
|
755
|
+
outputs = (latents,)
|
756
|
+
|
757
|
+
if return_noise:
|
758
|
+
outputs += (noise,)
|
759
|
+
|
760
|
+
if return_video_latents:
|
761
|
+
outputs += (video_latents,)
|
762
|
+
|
763
|
+
return outputs
|
764
|
+
|
765
|
+
@property
|
766
|
+
def guidance_scale(self):
|
767
|
+
return self._guidance_scale
|
768
|
+
|
769
|
+
@property
|
770
|
+
def guidance_rescale(self):
|
771
|
+
return self._guidance_rescale
|
772
|
+
|
773
|
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
774
|
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
775
|
+
# corresponds to doing no classifier free guidance.
|
776
|
+
@property
|
777
|
+
def do_classifier_free_guidance(self):
|
778
|
+
return self._guidance_scale > 1
|
779
|
+
|
780
|
+
@property
|
781
|
+
def num_timesteps(self):
|
782
|
+
return self._num_timesteps
|
783
|
+
|
784
|
+
@property
|
785
|
+
def interrupt(self):
|
786
|
+
return self._interrupt
|
787
|
+
|
788
|
+
@torch.no_grad()
|
789
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
790
|
+
def __call__(
|
791
|
+
self,
|
792
|
+
prompt: Union[str, List[str]] = None,
|
793
|
+
num_frames: Optional[int] = 49,
|
794
|
+
video: Union[torch.FloatTensor] = None,
|
795
|
+
mask_video: Union[torch.FloatTensor] = None,
|
796
|
+
masked_video_latents: Union[torch.FloatTensor] = None,
|
797
|
+
height: Optional[int] = 512,
|
798
|
+
width: Optional[int] = 512,
|
799
|
+
num_inference_steps: Optional[int] = 50,
|
800
|
+
guidance_scale: Optional[float] = 5.0,
|
801
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
802
|
+
num_images_per_prompt: Optional[int] = 1,
|
803
|
+
eta: Optional[float] = 0.0,
|
804
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
805
|
+
latents: Optional[torch.Tensor] = None,
|
806
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
807
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
808
|
+
prompt_attention_mask: Optional[torch.Tensor] = None,
|
809
|
+
negative_prompt_attention_mask: Optional[torch.Tensor] = None,
|
810
|
+
output_type: Optional[str] = "pil",
|
811
|
+
return_dict: bool = True,
|
812
|
+
callback_on_step_end: Optional[
|
813
|
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
814
|
+
] = None,
|
815
|
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
816
|
+
guidance_rescale: float = 0.0,
|
817
|
+
strength: float = 1.0,
|
818
|
+
noise_aug_strength: float = 0.0563,
|
819
|
+
timesteps: Optional[List[int]] = None,
|
820
|
+
):
|
821
|
+
r"""
|
822
|
+
The call function to the pipeline for generation with HunyuanDiT.
|
823
|
+
|
824
|
+
Examples:
|
825
|
+
prompt (`str` or `List[str]`, *optional*):
|
826
|
+
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
827
|
+
num_frames (`int`, *optional*):
|
828
|
+
Length of the video to be generated in seconds. This parameter influences the number of frames and
|
829
|
+
continuity of generated content.
|
830
|
+
video (`torch.FloatTensor`, *optional*):
|
831
|
+
A tensor representing an input video, which can be modified depending on the prompts provided.
|
832
|
+
mask_video (`torch.FloatTensor`, *optional*):
|
833
|
+
A tensor to specify areas of the video to be masked (omitted from generation).
|
834
|
+
masked_video_latents (`torch.FloatTensor`, *optional*):
|
835
|
+
Latents from masked portions of the video, utilized during image generation.
|
836
|
+
height (`int`, *optional*):
|
837
|
+
The height in pixels of the generated image or video frames.
|
838
|
+
width (`int`, *optional*):
|
839
|
+
The width in pixels of the generated image or video frames.
|
840
|
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
841
|
+
The number of denoising steps. More denoising steps usually lead to a higher quality image but slower
|
842
|
+
inference time. This parameter is modulated by `strength`.
|
843
|
+
guidance_scale (`float`, *optional*, defaults to 5.0):
|
844
|
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
845
|
+
`prompt` at the expense of lower image quality. Guidance scale is effective when `guidance_scale > 1`.
|
846
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
847
|
+
The prompt or prompts to guide what to exclude in image generation. If not defined, you need to provide
|
848
|
+
`negative_prompt_embeds`. This parameter is ignored when not using guidance (`guidance_scale < 1`).
|
849
|
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
850
|
+
The number of images to generate per prompt.
|
851
|
+
eta (`float`, *optional*, defaults to 0.0):
|
852
|
+
A parameter defined in the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies to the
|
853
|
+
[`~schedulers.DDIMScheduler`] and is ignored in other schedulers. It adjusts noise level during the
|
854
|
+
inference process.
|
855
|
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
856
|
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) for setting
|
857
|
+
random seeds which helps in making generation deterministic.
|
858
|
+
latents (`torch.Tensor`, *optional*):
|
859
|
+
A pre-computed latent representation which can be used to guide the generation process.
|
860
|
+
prompt_embeds (`torch.Tensor`, *optional*):
|
861
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
862
|
+
provided, embeddings are generated from the `prompt` input argument.
|
863
|
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
864
|
+
Pre-generated negative text embeddings, aiding in fine-tuning what should not be represented in the
|
865
|
+
outputs. If not provided, embeddings are generated from the `negative_prompt` argument.
|
866
|
+
prompt_attention_mask (`torch.Tensor`, *optional*):
|
867
|
+
Attention mask guiding the focus of the model on specific parts of the prompt text. Required when using
|
868
|
+
`prompt_embeds`.
|
869
|
+
negative_prompt_attention_mask (`torch.Tensor`, *optional*):
|
870
|
+
Attention mask for the negative prompt, needed when `negative_prompt_embeds` are used.
|
871
|
+
output_type (`str`, *optional*, defaults to `"latent"`):
|
872
|
+
The output format of the generated image. Choose between `PIL.Image` and `np.array` to define how you
|
873
|
+
want the results to be formatted.
|
874
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
875
|
+
If set to `True`, a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] will be returned;
|
876
|
+
otherwise, a tuple containing the generated images and safety flags will be returned.
|
877
|
+
callback_on_step_end (`Callable[[int, int, Dict], None]`, `PipelineCallback`, `MultiPipelineCallbacks`,
|
878
|
+
*optional*):
|
879
|
+
A callback function (or a list of them) that will be executed at the end of each denoising step,
|
880
|
+
allowing for custom processing during generation.
|
881
|
+
callback_on_step_end_tensor_inputs (`List[str]`, *optional*):
|
882
|
+
Specifies which tensor inputs should be included in the callback function. If not defined, all tensor
|
883
|
+
inputs will be passed, facilitating enhanced logging or monitoring of the generation process.
|
884
|
+
guidance_rescale (`float`, *optional*, defaults to 0.0):
|
885
|
+
Rescale parameter for adjusting noise configuration based on guidance rescale. Based on findings from
|
886
|
+
[Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
|
887
|
+
strength (`float`, *optional*, defaults to 1.0):
|
888
|
+
Affects the overall styling or quality of the generated output. Values closer to 1 usually provide
|
889
|
+
direct adherence to prompts.
|
890
|
+
|
891
|
+
Examples:
|
892
|
+
# Example usage of the function for generating images based on prompts.
|
893
|
+
|
894
|
+
Returns:
|
895
|
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
896
|
+
Returns either a structured output containing generated images and their metadata when `return_dict` is
|
897
|
+
`True`, or a simpler tuple, where the first element is a list of generated images and the second
|
898
|
+
element indicates if any of them contain "not-safe-for-work" (NSFW) content.
|
899
|
+
"""
|
900
|
+
|
901
|
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
902
|
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
903
|
+
|
904
|
+
# 0. default height and width
|
905
|
+
height = int(height // 16 * 16)
|
906
|
+
width = int(width // 16 * 16)
|
907
|
+
|
908
|
+
# 1. Check inputs. Raise error if not correct
|
909
|
+
self.check_inputs(
|
910
|
+
prompt,
|
911
|
+
height,
|
912
|
+
width,
|
913
|
+
negative_prompt,
|
914
|
+
prompt_embeds,
|
915
|
+
negative_prompt_embeds,
|
916
|
+
prompt_attention_mask,
|
917
|
+
negative_prompt_attention_mask,
|
918
|
+
callback_on_step_end_tensor_inputs,
|
919
|
+
)
|
920
|
+
self._guidance_scale = guidance_scale
|
921
|
+
self._guidance_rescale = guidance_rescale
|
922
|
+
self._interrupt = False
|
923
|
+
|
924
|
+
# 2. Define call parameters
|
925
|
+
if prompt is not None and isinstance(prompt, str):
|
926
|
+
batch_size = 1
|
927
|
+
elif prompt is not None and isinstance(prompt, list):
|
928
|
+
batch_size = len(prompt)
|
929
|
+
else:
|
930
|
+
batch_size = prompt_embeds.shape[0]
|
931
|
+
|
932
|
+
device = self._execution_device
|
933
|
+
if self.text_encoder is not None:
|
934
|
+
dtype = self.text_encoder.dtype
|
935
|
+
else:
|
936
|
+
dtype = self.transformer.dtype
|
937
|
+
|
938
|
+
# 3. Encode input prompt
|
939
|
+
(
|
940
|
+
prompt_embeds,
|
941
|
+
negative_prompt_embeds,
|
942
|
+
prompt_attention_mask,
|
943
|
+
negative_prompt_attention_mask,
|
944
|
+
) = self.encode_prompt(
|
945
|
+
prompt=prompt,
|
946
|
+
device=device,
|
947
|
+
dtype=dtype,
|
948
|
+
num_images_per_prompt=num_images_per_prompt,
|
949
|
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
950
|
+
negative_prompt=negative_prompt,
|
951
|
+
prompt_embeds=prompt_embeds,
|
952
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
953
|
+
prompt_attention_mask=prompt_attention_mask,
|
954
|
+
negative_prompt_attention_mask=negative_prompt_attention_mask,
|
955
|
+
)
|
956
|
+
|
957
|
+
# 4. set timesteps
|
958
|
+
if isinstance(self.scheduler, FlowMatchEulerDiscreteScheduler):
|
959
|
+
timesteps, num_inference_steps = retrieve_timesteps(
|
960
|
+
self.scheduler, num_inference_steps, device, timesteps, mu=1
|
961
|
+
)
|
962
|
+
else:
|
963
|
+
timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
|
964
|
+
timesteps, num_inference_steps = self.get_timesteps(
|
965
|
+
num_inference_steps=num_inference_steps, strength=strength, device=device
|
966
|
+
)
|
967
|
+
|
968
|
+
# at which timestep to set the initial noise (n.b. 50% if strength is 0.5)
|
969
|
+
latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
|
970
|
+
# create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise
|
971
|
+
is_strength_max = strength == 1.0
|
972
|
+
|
973
|
+
if video is not None:
|
974
|
+
batch_size, channels, num_frames, height_video, width_video = video.shape
|
975
|
+
init_video = self.image_processor.preprocess(
|
976
|
+
video.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, channels, height_video, width_video),
|
977
|
+
height=height,
|
978
|
+
width=width,
|
979
|
+
)
|
980
|
+
init_video = init_video.to(dtype=torch.float32)
|
981
|
+
init_video = init_video.reshape(batch_size, num_frames, channels, height, width).permute(0, 2, 1, 3, 4)
|
982
|
+
else:
|
983
|
+
init_video = None
|
984
|
+
|
985
|
+
# Prepare latent variables
|
986
|
+
num_channels_latents = self.vae.config.latent_channels
|
987
|
+
num_channels_transformer = self.transformer.config.in_channels
|
988
|
+
return_image_latents = num_channels_transformer == num_channels_latents
|
989
|
+
|
990
|
+
# 5. Prepare latents.
|
991
|
+
latents_outputs = self.prepare_latents(
|
992
|
+
batch_size * num_images_per_prompt,
|
993
|
+
num_channels_latents,
|
994
|
+
height,
|
995
|
+
width,
|
996
|
+
num_frames,
|
997
|
+
dtype,
|
998
|
+
device,
|
999
|
+
generator,
|
1000
|
+
latents,
|
1001
|
+
video=init_video,
|
1002
|
+
timestep=latent_timestep,
|
1003
|
+
is_strength_max=is_strength_max,
|
1004
|
+
return_noise=True,
|
1005
|
+
return_video_latents=return_image_latents,
|
1006
|
+
)
|
1007
|
+
if return_image_latents:
|
1008
|
+
latents, noise, image_latents = latents_outputs
|
1009
|
+
else:
|
1010
|
+
latents, noise = latents_outputs
|
1011
|
+
|
1012
|
+
# 6. Prepare inpaint latents if it needs.
|
1013
|
+
if mask_video is not None:
|
1014
|
+
if (mask_video == 255).all():
|
1015
|
+
mask = torch.zeros_like(latents).to(device, dtype)
|
1016
|
+
# Use zero latents if we want to t2v.
|
1017
|
+
if self.transformer.config.resize_inpaint_mask_directly:
|
1018
|
+
mask_latents = torch.zeros_like(latents)[:, :1].to(device, dtype)
|
1019
|
+
else:
|
1020
|
+
mask_latents = torch.zeros_like(latents).to(device, dtype)
|
1021
|
+
masked_video_latents = torch.zeros_like(latents).to(device, dtype)
|
1022
|
+
|
1023
|
+
mask_input = torch.cat([mask_latents] * 2) if self.do_classifier_free_guidance else mask_latents
|
1024
|
+
masked_video_latents_input = (
|
1025
|
+
torch.cat([masked_video_latents] * 2) if self.do_classifier_free_guidance else masked_video_latents
|
1026
|
+
)
|
1027
|
+
inpaint_latents = torch.cat([mask_input, masked_video_latents_input], dim=1).to(dtype)
|
1028
|
+
else:
|
1029
|
+
# Prepare mask latent variables
|
1030
|
+
batch_size, channels, num_frames, height_video, width_video = mask_video.shape
|
1031
|
+
mask_condition = self.mask_processor.preprocess(
|
1032
|
+
mask_video.permute(0, 2, 1, 3, 4).reshape(
|
1033
|
+
batch_size * num_frames, channels, height_video, width_video
|
1034
|
+
),
|
1035
|
+
height=height,
|
1036
|
+
width=width,
|
1037
|
+
)
|
1038
|
+
mask_condition = mask_condition.to(dtype=torch.float32)
|
1039
|
+
mask_condition = mask_condition.reshape(batch_size, num_frames, channels, height, width).permute(
|
1040
|
+
0, 2, 1, 3, 4
|
1041
|
+
)
|
1042
|
+
|
1043
|
+
if num_channels_transformer != num_channels_latents:
|
1044
|
+
mask_condition_tile = torch.tile(mask_condition, [1, 3, 1, 1, 1])
|
1045
|
+
if masked_video_latents is None:
|
1046
|
+
masked_video = (
|
1047
|
+
init_video * (mask_condition_tile < 0.5)
|
1048
|
+
+ torch.ones_like(init_video) * (mask_condition_tile > 0.5) * -1
|
1049
|
+
)
|
1050
|
+
else:
|
1051
|
+
masked_video = masked_video_latents
|
1052
|
+
|
1053
|
+
if self.transformer.config.resize_inpaint_mask_directly:
|
1054
|
+
_, masked_video_latents = self.prepare_mask_latents(
|
1055
|
+
None,
|
1056
|
+
masked_video,
|
1057
|
+
batch_size,
|
1058
|
+
height,
|
1059
|
+
width,
|
1060
|
+
dtype,
|
1061
|
+
device,
|
1062
|
+
generator,
|
1063
|
+
self.do_classifier_free_guidance,
|
1064
|
+
noise_aug_strength=noise_aug_strength,
|
1065
|
+
)
|
1066
|
+
mask_latents = resize_mask(
|
1067
|
+
1 - mask_condition, masked_video_latents, self.vae.config.cache_mag_vae
|
1068
|
+
)
|
1069
|
+
mask_latents = mask_latents.to(device, dtype) * self.vae.config.scaling_factor
|
1070
|
+
else:
|
1071
|
+
mask_latents, masked_video_latents = self.prepare_mask_latents(
|
1072
|
+
mask_condition_tile,
|
1073
|
+
masked_video,
|
1074
|
+
batch_size,
|
1075
|
+
height,
|
1076
|
+
width,
|
1077
|
+
dtype,
|
1078
|
+
device,
|
1079
|
+
generator,
|
1080
|
+
self.do_classifier_free_guidance,
|
1081
|
+
noise_aug_strength=noise_aug_strength,
|
1082
|
+
)
|
1083
|
+
|
1084
|
+
mask_input = torch.cat([mask_latents] * 2) if self.do_classifier_free_guidance else mask_latents
|
1085
|
+
masked_video_latents_input = (
|
1086
|
+
torch.cat([masked_video_latents] * 2)
|
1087
|
+
if self.do_classifier_free_guidance
|
1088
|
+
else masked_video_latents
|
1089
|
+
)
|
1090
|
+
inpaint_latents = torch.cat([mask_input, masked_video_latents_input], dim=1).to(dtype)
|
1091
|
+
else:
|
1092
|
+
inpaint_latents = None
|
1093
|
+
|
1094
|
+
mask = torch.tile(mask_condition, [1, num_channels_latents, 1, 1, 1])
|
1095
|
+
mask = F.interpolate(mask, size=latents.size()[-3:], mode="trilinear", align_corners=True).to(
|
1096
|
+
device, dtype
|
1097
|
+
)
|
1098
|
+
else:
|
1099
|
+
if num_channels_transformer != num_channels_latents:
|
1100
|
+
mask = torch.zeros_like(latents).to(device, dtype)
|
1101
|
+
if self.transformer.config.resize_inpaint_mask_directly:
|
1102
|
+
mask_latents = torch.zeros_like(latents)[:, :1].to(device, dtype)
|
1103
|
+
else:
|
1104
|
+
mask_latents = torch.zeros_like(latents).to(device, dtype)
|
1105
|
+
masked_video_latents = torch.zeros_like(latents).to(device, dtype)
|
1106
|
+
|
1107
|
+
mask_input = torch.cat([mask_latents] * 2) if self.do_classifier_free_guidance else mask_latents
|
1108
|
+
masked_video_latents_input = (
|
1109
|
+
torch.cat([masked_video_latents] * 2) if self.do_classifier_free_guidance else masked_video_latents
|
1110
|
+
)
|
1111
|
+
inpaint_latents = torch.cat([mask_input, masked_video_latents_input], dim=1).to(dtype)
|
1112
|
+
else:
|
1113
|
+
mask = torch.zeros_like(init_video[:, :1])
|
1114
|
+
mask = torch.tile(mask, [1, num_channels_latents, 1, 1, 1])
|
1115
|
+
mask = F.interpolate(mask, size=latents.size()[-3:], mode="trilinear", align_corners=True).to(
|
1116
|
+
device, dtype
|
1117
|
+
)
|
1118
|
+
|
1119
|
+
inpaint_latents = None
|
1120
|
+
|
1121
|
+
# Check that sizes of mask, masked image and latents match
|
1122
|
+
if num_channels_transformer != num_channels_latents:
|
1123
|
+
num_channels_mask = mask_latents.shape[1]
|
1124
|
+
num_channels_masked_image = masked_video_latents.shape[1]
|
1125
|
+
if (
|
1126
|
+
num_channels_latents + num_channels_mask + num_channels_masked_image
|
1127
|
+
!= self.transformer.config.in_channels
|
1128
|
+
):
|
1129
|
+
raise ValueError(
|
1130
|
+
f"Incorrect configuration settings! The config of `pipeline.transformer`: {self.transformer.config} expects"
|
1131
|
+
f" {self.transformer.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"
|
1132
|
+
f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}"
|
1133
|
+
f" = {num_channels_latents + num_channels_masked_image + num_channels_mask}. Please verify the config of"
|
1134
|
+
" `pipeline.transformer` or your `mask_image` or `image` input."
|
1135
|
+
)
|
1136
|
+
|
1137
|
+
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
1138
|
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
1139
|
+
|
1140
|
+
if self.do_classifier_free_guidance:
|
1141
|
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
1142
|
+
prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask])
|
1143
|
+
|
1144
|
+
# To latents.device
|
1145
|
+
prompt_embeds = prompt_embeds.to(device=device)
|
1146
|
+
prompt_attention_mask = prompt_attention_mask.to(device=device)
|
1147
|
+
|
1148
|
+
# 8. Denoising loop
|
1149
|
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
1150
|
+
self._num_timesteps = len(timesteps)
|
1151
|
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
1152
|
+
for i, t in enumerate(timesteps):
|
1153
|
+
if self.interrupt:
|
1154
|
+
continue
|
1155
|
+
|
1156
|
+
# expand the latents if we are doing classifier free guidance
|
1157
|
+
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
1158
|
+
if hasattr(self.scheduler, "scale_model_input"):
|
1159
|
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
1160
|
+
|
1161
|
+
# expand scalar t to 1-D tensor to match the 1st dim of latent_model_input
|
1162
|
+
t_expand = torch.tensor([t] * latent_model_input.shape[0], device=device).to(
|
1163
|
+
dtype=latent_model_input.dtype
|
1164
|
+
)
|
1165
|
+
|
1166
|
+
# predict the noise residual
|
1167
|
+
noise_pred = self.transformer(
|
1168
|
+
latent_model_input,
|
1169
|
+
t_expand,
|
1170
|
+
encoder_hidden_states=prompt_embeds,
|
1171
|
+
inpaint_latents=inpaint_latents,
|
1172
|
+
return_dict=False,
|
1173
|
+
)[0]
|
1174
|
+
if noise_pred.size()[1] != self.vae.config.latent_channels:
|
1175
|
+
noise_pred, _ = noise_pred.chunk(2, dim=1)
|
1176
|
+
|
1177
|
+
# perform guidance
|
1178
|
+
if self.do_classifier_free_guidance:
|
1179
|
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
1180
|
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
1181
|
+
|
1182
|
+
if self.do_classifier_free_guidance and guidance_rescale > 0.0:
|
1183
|
+
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
|
1184
|
+
noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
|
1185
|
+
|
1186
|
+
# compute the previous noisy sample x_t -> x_t-1
|
1187
|
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
1188
|
+
|
1189
|
+
if num_channels_transformer == num_channels_latents:
|
1190
|
+
init_latents_proper = image_latents
|
1191
|
+
init_mask = mask
|
1192
|
+
if i < len(timesteps) - 1:
|
1193
|
+
noise_timestep = timesteps[i + 1]
|
1194
|
+
if isinstance(self.scheduler, FlowMatchEulerDiscreteScheduler):
|
1195
|
+
init_latents_proper = self.scheduler.scale_noise(
|
1196
|
+
init_latents_proper, torch.tensor([noise_timestep], noise)
|
1197
|
+
)
|
1198
|
+
else:
|
1199
|
+
init_latents_proper = self.scheduler.add_noise(
|
1200
|
+
init_latents_proper, noise, torch.tensor([noise_timestep])
|
1201
|
+
)
|
1202
|
+
|
1203
|
+
latents = (1 - init_mask) * init_latents_proper + init_mask * latents
|
1204
|
+
|
1205
|
+
if callback_on_step_end is not None:
|
1206
|
+
callback_kwargs = {}
|
1207
|
+
for k in callback_on_step_end_tensor_inputs:
|
1208
|
+
callback_kwargs[k] = locals()[k]
|
1209
|
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
1210
|
+
|
1211
|
+
latents = callback_outputs.pop("latents", latents)
|
1212
|
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
1213
|
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
1214
|
+
|
1215
|
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
1216
|
+
progress_bar.update()
|
1217
|
+
|
1218
|
+
if XLA_AVAILABLE:
|
1219
|
+
xm.mark_step()
|
1220
|
+
|
1221
|
+
if not output_type == "latent":
|
1222
|
+
latents = 1 / self.vae.config.scaling_factor * latents
|
1223
|
+
video = self.vae.decode(latents, return_dict=False)[0]
|
1224
|
+
video = self.video_processor.postprocess_video(video=video, output_type=output_type)
|
1225
|
+
else:
|
1226
|
+
video = latents
|
1227
|
+
|
1228
|
+
# Offload all models
|
1229
|
+
self.maybe_free_model_hooks()
|
1230
|
+
|
1231
|
+
if not return_dict:
|
1232
|
+
return (video,)
|
1233
|
+
|
1234
|
+
return EasyAnimatePipelineOutput(frames=video)
|