diffusers 0.27.1__py3-none-any.whl → 0.32.2__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- diffusers/__init__.py +233 -6
- diffusers/callbacks.py +209 -0
- diffusers/commands/env.py +102 -6
- diffusers/configuration_utils.py +45 -16
- diffusers/dependency_versions_table.py +4 -3
- diffusers/image_processor.py +434 -110
- diffusers/loaders/__init__.py +42 -9
- diffusers/loaders/ip_adapter.py +626 -36
- diffusers/loaders/lora_base.py +900 -0
- diffusers/loaders/lora_conversion_utils.py +991 -125
- diffusers/loaders/lora_pipeline.py +3812 -0
- diffusers/loaders/peft.py +571 -7
- diffusers/loaders/single_file.py +405 -173
- diffusers/loaders/single_file_model.py +385 -0
- diffusers/loaders/single_file_utils.py +1783 -713
- diffusers/loaders/textual_inversion.py +41 -23
- diffusers/loaders/transformer_flux.py +181 -0
- diffusers/loaders/transformer_sd3.py +89 -0
- diffusers/loaders/unet.py +464 -540
- diffusers/loaders/unet_loader_utils.py +163 -0
- diffusers/models/__init__.py +76 -7
- diffusers/models/activations.py +65 -10
- diffusers/models/adapter.py +53 -53
- diffusers/models/attention.py +605 -18
- diffusers/models/attention_flax.py +1 -1
- diffusers/models/attention_processor.py +4304 -687
- diffusers/models/autoencoders/__init__.py +8 -0
- diffusers/models/autoencoders/autoencoder_asym_kl.py +15 -17
- diffusers/models/autoencoders/autoencoder_dc.py +620 -0
- diffusers/models/autoencoders/autoencoder_kl.py +110 -28
- diffusers/models/autoencoders/autoencoder_kl_allegro.py +1149 -0
- diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +1482 -0
- diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py +1176 -0
- diffusers/models/autoencoders/autoencoder_kl_ltx.py +1338 -0
- diffusers/models/autoencoders/autoencoder_kl_mochi.py +1166 -0
- diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +19 -24
- diffusers/models/autoencoders/autoencoder_oobleck.py +464 -0
- diffusers/models/autoencoders/autoencoder_tiny.py +21 -18
- diffusers/models/autoencoders/consistency_decoder_vae.py +45 -20
- diffusers/models/autoencoders/vae.py +41 -29
- diffusers/models/autoencoders/vq_model.py +182 -0
- diffusers/models/controlnet.py +47 -800
- diffusers/models/controlnet_flux.py +70 -0
- diffusers/models/controlnet_sd3.py +68 -0
- diffusers/models/controlnet_sparsectrl.py +116 -0
- diffusers/models/controlnets/__init__.py +23 -0
- diffusers/models/controlnets/controlnet.py +872 -0
- diffusers/models/{controlnet_flax.py → controlnets/controlnet_flax.py} +9 -9
- diffusers/models/controlnets/controlnet_flux.py +536 -0
- diffusers/models/controlnets/controlnet_hunyuan.py +401 -0
- diffusers/models/controlnets/controlnet_sd3.py +489 -0
- diffusers/models/controlnets/controlnet_sparsectrl.py +788 -0
- diffusers/models/controlnets/controlnet_union.py +832 -0
- diffusers/models/controlnets/controlnet_xs.py +1946 -0
- diffusers/models/controlnets/multicontrolnet.py +183 -0
- diffusers/models/downsampling.py +85 -18
- diffusers/models/embeddings.py +1856 -158
- diffusers/models/embeddings_flax.py +23 -9
- diffusers/models/model_loading_utils.py +480 -0
- diffusers/models/modeling_flax_pytorch_utils.py +2 -1
- diffusers/models/modeling_flax_utils.py +2 -7
- diffusers/models/modeling_outputs.py +14 -0
- diffusers/models/modeling_pytorch_flax_utils.py +1 -1
- diffusers/models/modeling_utils.py +611 -146
- diffusers/models/normalization.py +361 -20
- diffusers/models/resnet.py +18 -23
- diffusers/models/transformers/__init__.py +16 -0
- diffusers/models/transformers/auraflow_transformer_2d.py +544 -0
- diffusers/models/transformers/cogvideox_transformer_3d.py +542 -0
- diffusers/models/transformers/dit_transformer_2d.py +240 -0
- diffusers/models/transformers/dual_transformer_2d.py +9 -8
- diffusers/models/transformers/hunyuan_transformer_2d.py +578 -0
- diffusers/models/transformers/latte_transformer_3d.py +327 -0
- diffusers/models/transformers/lumina_nextdit2d.py +340 -0
- diffusers/models/transformers/pixart_transformer_2d.py +445 -0
- diffusers/models/transformers/prior_transformer.py +13 -13
- diffusers/models/transformers/sana_transformer.py +488 -0
- diffusers/models/transformers/stable_audio_transformer.py +458 -0
- diffusers/models/transformers/t5_film_transformer.py +17 -19
- diffusers/models/transformers/transformer_2d.py +297 -187
- diffusers/models/transformers/transformer_allegro.py +422 -0
- diffusers/models/transformers/transformer_cogview3plus.py +386 -0
- diffusers/models/transformers/transformer_flux.py +593 -0
- diffusers/models/transformers/transformer_hunyuan_video.py +791 -0
- diffusers/models/transformers/transformer_ltx.py +469 -0
- diffusers/models/transformers/transformer_mochi.py +499 -0
- diffusers/models/transformers/transformer_sd3.py +461 -0
- diffusers/models/transformers/transformer_temporal.py +21 -19
- diffusers/models/unets/unet_1d.py +8 -8
- diffusers/models/unets/unet_1d_blocks.py +31 -31
- diffusers/models/unets/unet_2d.py +17 -10
- diffusers/models/unets/unet_2d_blocks.py +225 -149
- diffusers/models/unets/unet_2d_condition.py +41 -40
- diffusers/models/unets/unet_2d_condition_flax.py +6 -5
- diffusers/models/unets/unet_3d_blocks.py +192 -1057
- diffusers/models/unets/unet_3d_condition.py +22 -27
- diffusers/models/unets/unet_i2vgen_xl.py +22 -18
- diffusers/models/unets/unet_kandinsky3.py +2 -2
- diffusers/models/unets/unet_motion_model.py +1413 -89
- diffusers/models/unets/unet_spatio_temporal_condition.py +40 -16
- diffusers/models/unets/unet_stable_cascade.py +19 -18
- diffusers/models/unets/uvit_2d.py +2 -2
- diffusers/models/upsampling.py +95 -26
- diffusers/models/vq_model.py +12 -164
- diffusers/optimization.py +1 -1
- diffusers/pipelines/__init__.py +202 -3
- diffusers/pipelines/allegro/__init__.py +48 -0
- diffusers/pipelines/allegro/pipeline_allegro.py +938 -0
- diffusers/pipelines/allegro/pipeline_output.py +23 -0
- diffusers/pipelines/amused/pipeline_amused.py +12 -12
- diffusers/pipelines/amused/pipeline_amused_img2img.py +14 -12
- diffusers/pipelines/amused/pipeline_amused_inpaint.py +13 -11
- diffusers/pipelines/animatediff/__init__.py +8 -0
- diffusers/pipelines/animatediff/pipeline_animatediff.py +122 -109
- diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +1106 -0
- diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +1288 -0
- diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +1010 -0
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +236 -180
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +1341 -0
- diffusers/pipelines/animatediff/pipeline_output.py +3 -2
- diffusers/pipelines/audioldm/pipeline_audioldm.py +14 -14
- diffusers/pipelines/audioldm2/modeling_audioldm2.py +58 -39
- diffusers/pipelines/audioldm2/pipeline_audioldm2.py +121 -36
- diffusers/pipelines/aura_flow/__init__.py +48 -0
- diffusers/pipelines/aura_flow/pipeline_aura_flow.py +584 -0
- diffusers/pipelines/auto_pipeline.py +196 -28
- diffusers/pipelines/blip_diffusion/blip_image_processing.py +1 -1
- diffusers/pipelines/blip_diffusion/modeling_blip2.py +6 -6
- diffusers/pipelines/blip_diffusion/modeling_ctx_clip.py +1 -1
- diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +2 -2
- diffusers/pipelines/cogvideo/__init__.py +54 -0
- diffusers/pipelines/cogvideo/pipeline_cogvideox.py +772 -0
- diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +825 -0
- diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +885 -0
- diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +851 -0
- diffusers/pipelines/cogvideo/pipeline_output.py +20 -0
- diffusers/pipelines/cogview3/__init__.py +47 -0
- diffusers/pipelines/cogview3/pipeline_cogview3plus.py +674 -0
- diffusers/pipelines/cogview3/pipeline_output.py +21 -0
- diffusers/pipelines/consistency_models/pipeline_consistency_models.py +6 -6
- diffusers/pipelines/controlnet/__init__.py +86 -80
- diffusers/pipelines/controlnet/multicontrolnet.py +7 -182
- diffusers/pipelines/controlnet/pipeline_controlnet.py +134 -87
- diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +2 -2
- diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +93 -77
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +88 -197
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +136 -90
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +176 -80
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +125 -89
- diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +1790 -0
- diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +1501 -0
- diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +1627 -0
- diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +2 -2
- diffusers/pipelines/controlnet_hunyuandit/__init__.py +48 -0
- diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +1060 -0
- diffusers/pipelines/controlnet_sd3/__init__.py +57 -0
- diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +1133 -0
- diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +1153 -0
- diffusers/pipelines/controlnet_xs/__init__.py +68 -0
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +916 -0
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +1111 -0
- diffusers/pipelines/ddpm/pipeline_ddpm.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_if.py +16 -30
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +20 -35
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +23 -41
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +22 -38
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +25 -41
- diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +19 -34
- diffusers/pipelines/deepfloyd_if/pipeline_output.py +6 -5
- diffusers/pipelines/deepfloyd_if/watermark.py +1 -1
- diffusers/pipelines/deprecated/alt_diffusion/modeling_roberta_series.py +11 -11
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +70 -30
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +48 -25
- diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +2 -2
- diffusers/pipelines/deprecated/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +7 -7
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +21 -20
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +27 -29
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +33 -27
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +33 -23
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +36 -30
- diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +102 -69
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py +13 -13
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +10 -5
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +11 -6
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +10 -5
- diffusers/pipelines/deprecated/vq_diffusion/pipeline_vq_diffusion.py +5 -5
- diffusers/pipelines/dit/pipeline_dit.py +7 -4
- diffusers/pipelines/flux/__init__.py +69 -0
- diffusers/pipelines/flux/modeling_flux.py +47 -0
- diffusers/pipelines/flux/pipeline_flux.py +957 -0
- diffusers/pipelines/flux/pipeline_flux_control.py +889 -0
- diffusers/pipelines/flux/pipeline_flux_control_img2img.py +945 -0
- diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +1141 -0
- diffusers/pipelines/flux/pipeline_flux_controlnet.py +1006 -0
- diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +998 -0
- diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +1204 -0
- diffusers/pipelines/flux/pipeline_flux_fill.py +969 -0
- diffusers/pipelines/flux/pipeline_flux_img2img.py +856 -0
- diffusers/pipelines/flux/pipeline_flux_inpaint.py +1022 -0
- diffusers/pipelines/flux/pipeline_flux_prior_redux.py +492 -0
- diffusers/pipelines/flux/pipeline_output.py +37 -0
- diffusers/pipelines/free_init_utils.py +41 -38
- diffusers/pipelines/free_noise_utils.py +596 -0
- diffusers/pipelines/hunyuan_video/__init__.py +48 -0
- diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +687 -0
- diffusers/pipelines/hunyuan_video/pipeline_output.py +20 -0
- diffusers/pipelines/hunyuandit/__init__.py +48 -0
- diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +916 -0
- diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +33 -48
- diffusers/pipelines/kandinsky/pipeline_kandinsky.py +8 -8
- diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +32 -29
- diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +11 -11
- diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +12 -12
- diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +10 -10
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +6 -6
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +34 -31
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +10 -10
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +10 -10
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +6 -6
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +8 -8
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +7 -7
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +6 -6
- diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.py +3 -3
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +22 -35
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +26 -37
- diffusers/pipelines/kolors/__init__.py +54 -0
- diffusers/pipelines/kolors/pipeline_kolors.py +1070 -0
- diffusers/pipelines/kolors/pipeline_kolors_img2img.py +1250 -0
- diffusers/pipelines/kolors/pipeline_output.py +21 -0
- diffusers/pipelines/kolors/text_encoder.py +889 -0
- diffusers/pipelines/kolors/tokenizer.py +338 -0
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +82 -62
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +77 -60
- diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +12 -12
- diffusers/pipelines/latte/__init__.py +48 -0
- diffusers/pipelines/latte/pipeline_latte.py +881 -0
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +80 -74
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +85 -76
- diffusers/pipelines/ledits_pp/pipeline_output.py +2 -2
- diffusers/pipelines/ltx/__init__.py +50 -0
- diffusers/pipelines/ltx/pipeline_ltx.py +789 -0
- diffusers/pipelines/ltx/pipeline_ltx_image2video.py +885 -0
- diffusers/pipelines/ltx/pipeline_output.py +20 -0
- diffusers/pipelines/lumina/__init__.py +48 -0
- diffusers/pipelines/lumina/pipeline_lumina.py +890 -0
- diffusers/pipelines/marigold/__init__.py +50 -0
- diffusers/pipelines/marigold/marigold_image_processing.py +576 -0
- diffusers/pipelines/marigold/pipeline_marigold_depth.py +813 -0
- diffusers/pipelines/marigold/pipeline_marigold_normals.py +690 -0
- diffusers/pipelines/mochi/__init__.py +48 -0
- diffusers/pipelines/mochi/pipeline_mochi.py +748 -0
- diffusers/pipelines/mochi/pipeline_output.py +20 -0
- diffusers/pipelines/musicldm/pipeline_musicldm.py +14 -14
- diffusers/pipelines/pag/__init__.py +80 -0
- diffusers/pipelines/pag/pag_utils.py +243 -0
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1328 -0
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +1543 -0
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +1610 -0
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +1683 -0
- diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +969 -0
- diffusers/pipelines/pag/pipeline_pag_kolors.py +1136 -0
- diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +865 -0
- diffusers/pipelines/pag/pipeline_pag_sana.py +886 -0
- diffusers/pipelines/pag/pipeline_pag_sd.py +1062 -0
- diffusers/pipelines/pag/pipeline_pag_sd_3.py +994 -0
- diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +1058 -0
- diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +866 -0
- diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +1094 -0
- diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +1356 -0
- diffusers/pipelines/pag/pipeline_pag_sd_xl.py +1345 -0
- diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +1544 -0
- diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +1776 -0
- diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +17 -12
- diffusers/pipelines/pia/pipeline_pia.py +74 -164
- diffusers/pipelines/pipeline_flax_utils.py +5 -10
- diffusers/pipelines/pipeline_loading_utils.py +515 -53
- diffusers/pipelines/pipeline_utils.py +411 -222
- diffusers/pipelines/pixart_alpha/__init__.py +8 -1
- diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +76 -93
- diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +873 -0
- diffusers/pipelines/sana/__init__.py +47 -0
- diffusers/pipelines/sana/pipeline_output.py +21 -0
- diffusers/pipelines/sana/pipeline_sana.py +884 -0
- diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +27 -23
- diffusers/pipelines/shap_e/pipeline_shap_e.py +3 -3
- diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +14 -14
- diffusers/pipelines/shap_e/renderer.py +1 -1
- diffusers/pipelines/stable_audio/__init__.py +50 -0
- diffusers/pipelines/stable_audio/modeling_stable_audio.py +158 -0
- diffusers/pipelines/stable_audio/pipeline_stable_audio.py +756 -0
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +71 -25
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +23 -19
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +35 -34
- diffusers/pipelines/stable_diffusion/__init__.py +0 -1
- diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +20 -11
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +2 -2
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +6 -6
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +145 -79
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +43 -28
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +13 -8
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +100 -68
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +109 -201
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +131 -32
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +247 -87
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +30 -29
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +35 -27
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +49 -42
- diffusers/pipelines/stable_diffusion/safety_checker.py +2 -1
- diffusers/pipelines/stable_diffusion_3/__init__.py +54 -0
- diffusers/pipelines/stable_diffusion_3/pipeline_output.py +21 -0
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +1140 -0
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +1036 -0
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +1250 -0
- diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +29 -20
- diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +59 -58
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +31 -25
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +38 -22
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +30 -24
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +24 -23
- diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +107 -67
- diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +316 -69
- diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +10 -5
- diffusers/pipelines/stable_diffusion_safe/safety_checker.py +1 -1
- diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +98 -30
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +121 -83
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +161 -105
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +142 -218
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +45 -29
- diffusers/pipelines/stable_diffusion_xl/watermark.py +9 -3
- diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +110 -57
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +69 -39
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +105 -74
- diffusers/pipelines/text_to_video_synthesis/pipeline_output.py +3 -2
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +29 -49
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +32 -93
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +37 -25
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +54 -40
- diffusers/pipelines/unclip/pipeline_unclip.py +6 -6
- diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +6 -6
- diffusers/pipelines/unidiffuser/modeling_text_decoder.py +1 -1
- diffusers/pipelines/unidiffuser/modeling_uvit.py +12 -12
- diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +29 -28
- diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +5 -5
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +5 -10
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +6 -8
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +4 -4
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +12 -12
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +15 -14
- diffusers/{models/dual_transformer_2d.py → quantizers/__init__.py} +2 -6
- diffusers/quantizers/auto.py +139 -0
- diffusers/quantizers/base.py +233 -0
- diffusers/quantizers/bitsandbytes/__init__.py +2 -0
- diffusers/quantizers/bitsandbytes/bnb_quantizer.py +561 -0
- diffusers/quantizers/bitsandbytes/utils.py +306 -0
- diffusers/quantizers/gguf/__init__.py +1 -0
- diffusers/quantizers/gguf/gguf_quantizer.py +159 -0
- diffusers/quantizers/gguf/utils.py +456 -0
- diffusers/quantizers/quantization_config.py +669 -0
- diffusers/quantizers/torchao/__init__.py +15 -0
- diffusers/quantizers/torchao/torchao_quantizer.py +292 -0
- diffusers/schedulers/__init__.py +12 -2
- diffusers/schedulers/deprecated/__init__.py +1 -1
- diffusers/schedulers/deprecated/scheduling_karras_ve.py +25 -25
- diffusers/schedulers/scheduling_amused.py +5 -5
- diffusers/schedulers/scheduling_consistency_decoder.py +11 -11
- diffusers/schedulers/scheduling_consistency_models.py +23 -25
- diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +572 -0
- diffusers/schedulers/scheduling_ddim.py +27 -26
- diffusers/schedulers/scheduling_ddim_cogvideox.py +452 -0
- diffusers/schedulers/scheduling_ddim_flax.py +2 -1
- diffusers/schedulers/scheduling_ddim_inverse.py +16 -16
- diffusers/schedulers/scheduling_ddim_parallel.py +32 -31
- diffusers/schedulers/scheduling_ddpm.py +27 -30
- diffusers/schedulers/scheduling_ddpm_flax.py +7 -3
- diffusers/schedulers/scheduling_ddpm_parallel.py +33 -36
- diffusers/schedulers/scheduling_ddpm_wuerstchen.py +14 -14
- diffusers/schedulers/scheduling_deis_multistep.py +150 -50
- diffusers/schedulers/scheduling_dpm_cogvideox.py +489 -0
- diffusers/schedulers/scheduling_dpmsolver_multistep.py +221 -84
- diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py +2 -2
- diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +158 -52
- diffusers/schedulers/scheduling_dpmsolver_sde.py +153 -34
- diffusers/schedulers/scheduling_dpmsolver_singlestep.py +275 -86
- diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +81 -57
- diffusers/schedulers/scheduling_edm_euler.py +62 -39
- diffusers/schedulers/scheduling_euler_ancestral_discrete.py +30 -29
- diffusers/schedulers/scheduling_euler_discrete.py +255 -74
- diffusers/schedulers/scheduling_flow_match_euler_discrete.py +458 -0
- diffusers/schedulers/scheduling_flow_match_heun_discrete.py +320 -0
- diffusers/schedulers/scheduling_heun_discrete.py +174 -46
- diffusers/schedulers/scheduling_ipndm.py +9 -9
- diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +138 -29
- diffusers/schedulers/scheduling_k_dpm_2_discrete.py +132 -26
- diffusers/schedulers/scheduling_karras_ve_flax.py +6 -6
- diffusers/schedulers/scheduling_lcm.py +23 -29
- diffusers/schedulers/scheduling_lms_discrete.py +105 -28
- diffusers/schedulers/scheduling_pndm.py +20 -20
- diffusers/schedulers/scheduling_repaint.py +21 -21
- diffusers/schedulers/scheduling_sasolver.py +157 -60
- diffusers/schedulers/scheduling_sde_ve.py +19 -19
- diffusers/schedulers/scheduling_tcd.py +41 -36
- diffusers/schedulers/scheduling_unclip.py +19 -16
- diffusers/schedulers/scheduling_unipc_multistep.py +243 -47
- diffusers/schedulers/scheduling_utils.py +12 -5
- diffusers/schedulers/scheduling_utils_flax.py +1 -3
- diffusers/schedulers/scheduling_vq_diffusion.py +10 -10
- diffusers/training_utils.py +214 -30
- diffusers/utils/__init__.py +17 -1
- diffusers/utils/constants.py +3 -0
- diffusers/utils/doc_utils.py +1 -0
- diffusers/utils/dummy_pt_objects.py +592 -7
- diffusers/utils/dummy_torch_and_torchsde_objects.py +15 -0
- diffusers/utils/dummy_torch_and_transformers_and_sentencepiece_objects.py +47 -0
- diffusers/utils/dummy_torch_and_transformers_objects.py +1001 -71
- diffusers/utils/dynamic_modules_utils.py +34 -29
- diffusers/utils/export_utils.py +50 -6
- diffusers/utils/hub_utils.py +131 -17
- diffusers/utils/import_utils.py +210 -8
- diffusers/utils/loading_utils.py +118 -5
- diffusers/utils/logging.py +4 -2
- diffusers/utils/peft_utils.py +37 -7
- diffusers/utils/state_dict_utils.py +13 -2
- diffusers/utils/testing_utils.py +193 -11
- diffusers/utils/torch_utils.py +4 -0
- diffusers/video_processor.py +113 -0
- {diffusers-0.27.1.dist-info → diffusers-0.32.2.dist-info}/METADATA +82 -91
- diffusers-0.32.2.dist-info/RECORD +550 -0
- {diffusers-0.27.1.dist-info → diffusers-0.32.2.dist-info}/WHEEL +1 -1
- diffusers/loaders/autoencoder.py +0 -146
- diffusers/loaders/controlnet.py +0 -136
- diffusers/loaders/lora.py +0 -1349
- diffusers/models/prior_transformer.py +0 -12
- diffusers/models/t5_film_transformer.py +0 -70
- diffusers/models/transformer_2d.py +0 -25
- diffusers/models/transformer_temporal.py +0 -34
- diffusers/models/unet_1d.py +0 -26
- diffusers/models/unet_1d_blocks.py +0 -203
- diffusers/models/unet_2d.py +0 -27
- diffusers/models/unet_2d_blocks.py +0 -375
- diffusers/models/unet_2d_condition.py +0 -25
- diffusers-0.27.1.dist-info/RECORD +0 -399
- {diffusers-0.27.1.dist-info → diffusers-0.32.2.dist-info}/LICENSE +0 -0
- {diffusers-0.27.1.dist-info → diffusers-0.32.2.dist-info}/entry_points.txt +0 -0
- {diffusers-0.27.1.dist-info → diffusers-0.32.2.dist-info}/top_level.txt +0 -0
@@ -11,15 +11,20 @@
|
|
11
11
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
12
|
# See the License for the specific language governing permissions and
|
13
13
|
# limitations under the License.
|
14
|
+
|
15
|
+
from dataclasses import dataclass
|
14
16
|
from typing import Any, Dict, Optional, Tuple, Union
|
15
17
|
|
16
18
|
import torch
|
17
19
|
import torch.nn as nn
|
20
|
+
import torch.nn.functional as F
|
18
21
|
import torch.utils.checkpoint
|
19
22
|
|
20
|
-
from ...configuration_utils import ConfigMixin, register_to_config
|
21
|
-
from ...loaders import UNet2DConditionLoadersMixin
|
22
|
-
from ...utils import logging
|
23
|
+
from ...configuration_utils import ConfigMixin, FrozenDict, register_to_config
|
24
|
+
from ...loaders import FromOriginalModelMixin, PeftAdapterMixin, UNet2DConditionLoadersMixin
|
25
|
+
from ...utils import BaseOutput, deprecate, is_torch_version, logging
|
26
|
+
from ...utils.torch_utils import apply_freeu
|
27
|
+
from ..attention import BasicTransformerBlock
|
23
28
|
from ..attention_processor import (
|
24
29
|
ADDED_KV_ATTENTION_PROCESSORS,
|
25
30
|
CROSS_ATTENTION_PROCESSORS,
|
@@ -27,33 +32,1094 @@ from ..attention_processor import (
|
|
27
32
|
AttentionProcessor,
|
28
33
|
AttnAddedKVProcessor,
|
29
34
|
AttnProcessor,
|
35
|
+
AttnProcessor2_0,
|
36
|
+
FusedAttnProcessor2_0,
|
37
|
+
IPAdapterAttnProcessor,
|
38
|
+
IPAdapterAttnProcessor2_0,
|
30
39
|
)
|
31
40
|
from ..embeddings import TimestepEmbedding, Timesteps
|
32
41
|
from ..modeling_utils import ModelMixin
|
33
|
-
from ..
|
42
|
+
from ..resnet import Downsample2D, ResnetBlock2D, Upsample2D
|
43
|
+
from ..transformers.dual_transformer_2d import DualTransformer2DModel
|
44
|
+
from ..transformers.transformer_2d import Transformer2DModel
|
34
45
|
from .unet_2d_blocks import UNetMidBlock2DCrossAttn
|
35
46
|
from .unet_2d_condition import UNet2DConditionModel
|
36
|
-
from .unet_3d_blocks import (
|
37
|
-
CrossAttnDownBlockMotion,
|
38
|
-
CrossAttnUpBlockMotion,
|
39
|
-
DownBlockMotion,
|
40
|
-
UNetMidBlockCrossAttnMotion,
|
41
|
-
UpBlockMotion,
|
42
|
-
get_down_block,
|
43
|
-
get_up_block,
|
44
|
-
)
|
45
|
-
from .unet_3d_condition import UNet3DConditionOutput
|
46
47
|
|
47
48
|
|
48
49
|
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
49
50
|
|
50
51
|
|
52
|
+
@dataclass
|
53
|
+
class UNetMotionOutput(BaseOutput):
|
54
|
+
"""
|
55
|
+
The output of [`UNetMotionOutput`].
|
56
|
+
|
57
|
+
Args:
|
58
|
+
sample (`torch.Tensor` of shape `(batch_size, num_channels, num_frames, height, width)`):
|
59
|
+
The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.
|
60
|
+
"""
|
61
|
+
|
62
|
+
sample: torch.Tensor
|
63
|
+
|
64
|
+
|
65
|
+
class AnimateDiffTransformer3D(nn.Module):
|
66
|
+
"""
|
67
|
+
A Transformer model for video-like data.
|
68
|
+
|
69
|
+
Parameters:
|
70
|
+
num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
|
71
|
+
attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
|
72
|
+
in_channels (`int`, *optional*):
|
73
|
+
The number of channels in the input and output (specify if the input is **continuous**).
|
74
|
+
num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
|
75
|
+
dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
|
76
|
+
cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
|
77
|
+
attention_bias (`bool`, *optional*):
|
78
|
+
Configure if the `TransformerBlock` attention should contain a bias parameter.
|
79
|
+
sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**).
|
80
|
+
This is fixed during training since it is used to learn a number of position embeddings.
|
81
|
+
activation_fn (`str`, *optional*, defaults to `"geglu"`):
|
82
|
+
Activation function to use in feed-forward. See `diffusers.models.activations.get_activation` for supported
|
83
|
+
activation functions.
|
84
|
+
norm_elementwise_affine (`bool`, *optional*):
|
85
|
+
Configure if the `TransformerBlock` should use learnable elementwise affine parameters for normalization.
|
86
|
+
double_self_attention (`bool`, *optional*):
|
87
|
+
Configure if each `TransformerBlock` should contain two self-attention layers.
|
88
|
+
positional_embeddings: (`str`, *optional*):
|
89
|
+
The type of positional embeddings to apply to the sequence input before passing use.
|
90
|
+
num_positional_embeddings: (`int`, *optional*):
|
91
|
+
The maximum length of the sequence over which to apply positional embeddings.
|
92
|
+
"""
|
93
|
+
|
94
|
+
def __init__(
|
95
|
+
self,
|
96
|
+
num_attention_heads: int = 16,
|
97
|
+
attention_head_dim: int = 88,
|
98
|
+
in_channels: Optional[int] = None,
|
99
|
+
out_channels: Optional[int] = None,
|
100
|
+
num_layers: int = 1,
|
101
|
+
dropout: float = 0.0,
|
102
|
+
norm_num_groups: int = 32,
|
103
|
+
cross_attention_dim: Optional[int] = None,
|
104
|
+
attention_bias: bool = False,
|
105
|
+
sample_size: Optional[int] = None,
|
106
|
+
activation_fn: str = "geglu",
|
107
|
+
norm_elementwise_affine: bool = True,
|
108
|
+
double_self_attention: bool = True,
|
109
|
+
positional_embeddings: Optional[str] = None,
|
110
|
+
num_positional_embeddings: Optional[int] = None,
|
111
|
+
):
|
112
|
+
super().__init__()
|
113
|
+
self.num_attention_heads = num_attention_heads
|
114
|
+
self.attention_head_dim = attention_head_dim
|
115
|
+
inner_dim = num_attention_heads * attention_head_dim
|
116
|
+
|
117
|
+
self.in_channels = in_channels
|
118
|
+
|
119
|
+
self.norm = nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True)
|
120
|
+
self.proj_in = nn.Linear(in_channels, inner_dim)
|
121
|
+
|
122
|
+
# 3. Define transformers blocks
|
123
|
+
self.transformer_blocks = nn.ModuleList(
|
124
|
+
[
|
125
|
+
BasicTransformerBlock(
|
126
|
+
inner_dim,
|
127
|
+
num_attention_heads,
|
128
|
+
attention_head_dim,
|
129
|
+
dropout=dropout,
|
130
|
+
cross_attention_dim=cross_attention_dim,
|
131
|
+
activation_fn=activation_fn,
|
132
|
+
attention_bias=attention_bias,
|
133
|
+
double_self_attention=double_self_attention,
|
134
|
+
norm_elementwise_affine=norm_elementwise_affine,
|
135
|
+
positional_embeddings=positional_embeddings,
|
136
|
+
num_positional_embeddings=num_positional_embeddings,
|
137
|
+
)
|
138
|
+
for _ in range(num_layers)
|
139
|
+
]
|
140
|
+
)
|
141
|
+
|
142
|
+
self.proj_out = nn.Linear(inner_dim, in_channels)
|
143
|
+
|
144
|
+
def forward(
|
145
|
+
self,
|
146
|
+
hidden_states: torch.Tensor,
|
147
|
+
encoder_hidden_states: Optional[torch.LongTensor] = None,
|
148
|
+
timestep: Optional[torch.LongTensor] = None,
|
149
|
+
class_labels: Optional[torch.LongTensor] = None,
|
150
|
+
num_frames: int = 1,
|
151
|
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
152
|
+
) -> torch.Tensor:
|
153
|
+
"""
|
154
|
+
The [`AnimateDiffTransformer3D`] forward method.
|
155
|
+
|
156
|
+
Args:
|
157
|
+
hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.Tensor` of shape `(batch size, channel, height, width)` if continuous):
|
158
|
+
Input hidden_states.
|
159
|
+
encoder_hidden_states ( `torch.LongTensor` of shape `(batch size, encoder_hidden_states dim)`, *optional*):
|
160
|
+
Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
|
161
|
+
self-attention.
|
162
|
+
timestep ( `torch.LongTensor`, *optional*):
|
163
|
+
Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
|
164
|
+
class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
|
165
|
+
Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in
|
166
|
+
`AdaLayerZeroNorm`.
|
167
|
+
num_frames (`int`, *optional*, defaults to 1):
|
168
|
+
The number of frames to be processed per batch. This is used to reshape the hidden states.
|
169
|
+
cross_attention_kwargs (`dict`, *optional*):
|
170
|
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
171
|
+
`self.processor` in
|
172
|
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
173
|
+
|
174
|
+
Returns:
|
175
|
+
torch.Tensor:
|
176
|
+
The output tensor.
|
177
|
+
"""
|
178
|
+
# 1. Input
|
179
|
+
batch_frames, channel, height, width = hidden_states.shape
|
180
|
+
batch_size = batch_frames // num_frames
|
181
|
+
|
182
|
+
residual = hidden_states
|
183
|
+
|
184
|
+
hidden_states = hidden_states[None, :].reshape(batch_size, num_frames, channel, height, width)
|
185
|
+
hidden_states = hidden_states.permute(0, 2, 1, 3, 4)
|
186
|
+
|
187
|
+
hidden_states = self.norm(hidden_states)
|
188
|
+
hidden_states = hidden_states.permute(0, 3, 4, 2, 1).reshape(batch_size * height * width, num_frames, channel)
|
189
|
+
|
190
|
+
hidden_states = self.proj_in(input=hidden_states)
|
191
|
+
|
192
|
+
# 2. Blocks
|
193
|
+
for block in self.transformer_blocks:
|
194
|
+
hidden_states = block(
|
195
|
+
hidden_states=hidden_states,
|
196
|
+
encoder_hidden_states=encoder_hidden_states,
|
197
|
+
timestep=timestep,
|
198
|
+
cross_attention_kwargs=cross_attention_kwargs,
|
199
|
+
class_labels=class_labels,
|
200
|
+
)
|
201
|
+
|
202
|
+
# 3. Output
|
203
|
+
hidden_states = self.proj_out(input=hidden_states)
|
204
|
+
hidden_states = (
|
205
|
+
hidden_states[None, None, :]
|
206
|
+
.reshape(batch_size, height, width, num_frames, channel)
|
207
|
+
.permute(0, 3, 4, 1, 2)
|
208
|
+
.contiguous()
|
209
|
+
)
|
210
|
+
hidden_states = hidden_states.reshape(batch_frames, channel, height, width)
|
211
|
+
|
212
|
+
output = hidden_states + residual
|
213
|
+
return output
|
214
|
+
|
215
|
+
|
216
|
+
class DownBlockMotion(nn.Module):
|
217
|
+
def __init__(
|
218
|
+
self,
|
219
|
+
in_channels: int,
|
220
|
+
out_channels: int,
|
221
|
+
temb_channels: int,
|
222
|
+
dropout: float = 0.0,
|
223
|
+
num_layers: int = 1,
|
224
|
+
resnet_eps: float = 1e-6,
|
225
|
+
resnet_time_scale_shift: str = "default",
|
226
|
+
resnet_act_fn: str = "swish",
|
227
|
+
resnet_groups: int = 32,
|
228
|
+
resnet_pre_norm: bool = True,
|
229
|
+
output_scale_factor: float = 1.0,
|
230
|
+
add_downsample: bool = True,
|
231
|
+
downsample_padding: int = 1,
|
232
|
+
temporal_num_attention_heads: Union[int, Tuple[int]] = 1,
|
233
|
+
temporal_cross_attention_dim: Optional[int] = None,
|
234
|
+
temporal_max_seq_length: int = 32,
|
235
|
+
temporal_transformer_layers_per_block: Union[int, Tuple[int]] = 1,
|
236
|
+
temporal_double_self_attention: bool = True,
|
237
|
+
):
|
238
|
+
super().__init__()
|
239
|
+
resnets = []
|
240
|
+
motion_modules = []
|
241
|
+
|
242
|
+
# support for variable transformer layers per temporal block
|
243
|
+
if isinstance(temporal_transformer_layers_per_block, int):
|
244
|
+
temporal_transformer_layers_per_block = (temporal_transformer_layers_per_block,) * num_layers
|
245
|
+
elif len(temporal_transformer_layers_per_block) != num_layers:
|
246
|
+
raise ValueError(
|
247
|
+
f"`temporal_transformer_layers_per_block` must be an integer or a tuple of integers of length {num_layers}"
|
248
|
+
)
|
249
|
+
|
250
|
+
# support for variable number of attention head per temporal layers
|
251
|
+
if isinstance(temporal_num_attention_heads, int):
|
252
|
+
temporal_num_attention_heads = (temporal_num_attention_heads,) * num_layers
|
253
|
+
elif len(temporal_num_attention_heads) != num_layers:
|
254
|
+
raise ValueError(
|
255
|
+
f"`temporal_num_attention_heads` must be an integer or a tuple of integers of length {num_layers}"
|
256
|
+
)
|
257
|
+
|
258
|
+
for i in range(num_layers):
|
259
|
+
in_channels = in_channels if i == 0 else out_channels
|
260
|
+
resnets.append(
|
261
|
+
ResnetBlock2D(
|
262
|
+
in_channels=in_channels,
|
263
|
+
out_channels=out_channels,
|
264
|
+
temb_channels=temb_channels,
|
265
|
+
eps=resnet_eps,
|
266
|
+
groups=resnet_groups,
|
267
|
+
dropout=dropout,
|
268
|
+
time_embedding_norm=resnet_time_scale_shift,
|
269
|
+
non_linearity=resnet_act_fn,
|
270
|
+
output_scale_factor=output_scale_factor,
|
271
|
+
pre_norm=resnet_pre_norm,
|
272
|
+
)
|
273
|
+
)
|
274
|
+
motion_modules.append(
|
275
|
+
AnimateDiffTransformer3D(
|
276
|
+
num_attention_heads=temporal_num_attention_heads[i],
|
277
|
+
in_channels=out_channels,
|
278
|
+
num_layers=temporal_transformer_layers_per_block[i],
|
279
|
+
norm_num_groups=resnet_groups,
|
280
|
+
cross_attention_dim=temporal_cross_attention_dim,
|
281
|
+
attention_bias=False,
|
282
|
+
activation_fn="geglu",
|
283
|
+
positional_embeddings="sinusoidal",
|
284
|
+
num_positional_embeddings=temporal_max_seq_length,
|
285
|
+
attention_head_dim=out_channels // temporal_num_attention_heads[i],
|
286
|
+
double_self_attention=temporal_double_self_attention,
|
287
|
+
)
|
288
|
+
)
|
289
|
+
|
290
|
+
self.resnets = nn.ModuleList(resnets)
|
291
|
+
self.motion_modules = nn.ModuleList(motion_modules)
|
292
|
+
|
293
|
+
if add_downsample:
|
294
|
+
self.downsamplers = nn.ModuleList(
|
295
|
+
[
|
296
|
+
Downsample2D(
|
297
|
+
out_channels,
|
298
|
+
use_conv=True,
|
299
|
+
out_channels=out_channels,
|
300
|
+
padding=downsample_padding,
|
301
|
+
name="op",
|
302
|
+
)
|
303
|
+
]
|
304
|
+
)
|
305
|
+
else:
|
306
|
+
self.downsamplers = None
|
307
|
+
|
308
|
+
self.gradient_checkpointing = False
|
309
|
+
|
310
|
+
def forward(
|
311
|
+
self,
|
312
|
+
hidden_states: torch.Tensor,
|
313
|
+
temb: Optional[torch.Tensor] = None,
|
314
|
+
num_frames: int = 1,
|
315
|
+
*args,
|
316
|
+
**kwargs,
|
317
|
+
) -> Union[torch.Tensor, Tuple[torch.Tensor, ...]]:
|
318
|
+
if len(args) > 0 or kwargs.get("scale", None) is not None:
|
319
|
+
deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
|
320
|
+
deprecate("scale", "1.0.0", deprecation_message)
|
321
|
+
|
322
|
+
output_states = ()
|
323
|
+
|
324
|
+
blocks = zip(self.resnets, self.motion_modules)
|
325
|
+
for resnet, motion_module in blocks:
|
326
|
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
327
|
+
|
328
|
+
def create_custom_forward(module):
|
329
|
+
def custom_forward(*inputs):
|
330
|
+
return module(*inputs)
|
331
|
+
|
332
|
+
return custom_forward
|
333
|
+
|
334
|
+
if is_torch_version(">=", "1.11.0"):
|
335
|
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
336
|
+
create_custom_forward(resnet),
|
337
|
+
hidden_states,
|
338
|
+
temb,
|
339
|
+
use_reentrant=False,
|
340
|
+
)
|
341
|
+
else:
|
342
|
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
343
|
+
create_custom_forward(resnet), hidden_states, temb
|
344
|
+
)
|
345
|
+
|
346
|
+
else:
|
347
|
+
hidden_states = resnet(input_tensor=hidden_states, temb=temb)
|
348
|
+
|
349
|
+
hidden_states = motion_module(hidden_states, num_frames=num_frames)
|
350
|
+
|
351
|
+
output_states = output_states + (hidden_states,)
|
352
|
+
|
353
|
+
if self.downsamplers is not None:
|
354
|
+
for downsampler in self.downsamplers:
|
355
|
+
hidden_states = downsampler(hidden_states=hidden_states)
|
356
|
+
|
357
|
+
output_states = output_states + (hidden_states,)
|
358
|
+
|
359
|
+
return hidden_states, output_states
|
360
|
+
|
361
|
+
|
362
|
+
class CrossAttnDownBlockMotion(nn.Module):
|
363
|
+
def __init__(
|
364
|
+
self,
|
365
|
+
in_channels: int,
|
366
|
+
out_channels: int,
|
367
|
+
temb_channels: int,
|
368
|
+
dropout: float = 0.0,
|
369
|
+
num_layers: int = 1,
|
370
|
+
transformer_layers_per_block: Union[int, Tuple[int]] = 1,
|
371
|
+
resnet_eps: float = 1e-6,
|
372
|
+
resnet_time_scale_shift: str = "default",
|
373
|
+
resnet_act_fn: str = "swish",
|
374
|
+
resnet_groups: int = 32,
|
375
|
+
resnet_pre_norm: bool = True,
|
376
|
+
num_attention_heads: int = 1,
|
377
|
+
cross_attention_dim: int = 1280,
|
378
|
+
output_scale_factor: float = 1.0,
|
379
|
+
downsample_padding: int = 1,
|
380
|
+
add_downsample: bool = True,
|
381
|
+
dual_cross_attention: bool = False,
|
382
|
+
use_linear_projection: bool = False,
|
383
|
+
only_cross_attention: bool = False,
|
384
|
+
upcast_attention: bool = False,
|
385
|
+
attention_type: str = "default",
|
386
|
+
temporal_cross_attention_dim: Optional[int] = None,
|
387
|
+
temporal_num_attention_heads: int = 8,
|
388
|
+
temporal_max_seq_length: int = 32,
|
389
|
+
temporal_transformer_layers_per_block: Union[int, Tuple[int]] = 1,
|
390
|
+
temporal_double_self_attention: bool = True,
|
391
|
+
):
|
392
|
+
super().__init__()
|
393
|
+
resnets = []
|
394
|
+
attentions = []
|
395
|
+
motion_modules = []
|
396
|
+
|
397
|
+
self.has_cross_attention = True
|
398
|
+
self.num_attention_heads = num_attention_heads
|
399
|
+
|
400
|
+
# support for variable transformer layers per block
|
401
|
+
if isinstance(transformer_layers_per_block, int):
|
402
|
+
transformer_layers_per_block = (transformer_layers_per_block,) * num_layers
|
403
|
+
elif len(transformer_layers_per_block) != num_layers:
|
404
|
+
raise ValueError(
|
405
|
+
f"transformer_layers_per_block must be an integer or a list of integers of length {num_layers}"
|
406
|
+
)
|
407
|
+
|
408
|
+
# support for variable transformer layers per temporal block
|
409
|
+
if isinstance(temporal_transformer_layers_per_block, int):
|
410
|
+
temporal_transformer_layers_per_block = (temporal_transformer_layers_per_block,) * num_layers
|
411
|
+
elif len(temporal_transformer_layers_per_block) != num_layers:
|
412
|
+
raise ValueError(
|
413
|
+
f"temporal_transformer_layers_per_block must be an integer or a list of integers of length {num_layers}"
|
414
|
+
)
|
415
|
+
|
416
|
+
for i in range(num_layers):
|
417
|
+
in_channels = in_channels if i == 0 else out_channels
|
418
|
+
resnets.append(
|
419
|
+
ResnetBlock2D(
|
420
|
+
in_channels=in_channels,
|
421
|
+
out_channels=out_channels,
|
422
|
+
temb_channels=temb_channels,
|
423
|
+
eps=resnet_eps,
|
424
|
+
groups=resnet_groups,
|
425
|
+
dropout=dropout,
|
426
|
+
time_embedding_norm=resnet_time_scale_shift,
|
427
|
+
non_linearity=resnet_act_fn,
|
428
|
+
output_scale_factor=output_scale_factor,
|
429
|
+
pre_norm=resnet_pre_norm,
|
430
|
+
)
|
431
|
+
)
|
432
|
+
|
433
|
+
if not dual_cross_attention:
|
434
|
+
attentions.append(
|
435
|
+
Transformer2DModel(
|
436
|
+
num_attention_heads,
|
437
|
+
out_channels // num_attention_heads,
|
438
|
+
in_channels=out_channels,
|
439
|
+
num_layers=transformer_layers_per_block[i],
|
440
|
+
cross_attention_dim=cross_attention_dim,
|
441
|
+
norm_num_groups=resnet_groups,
|
442
|
+
use_linear_projection=use_linear_projection,
|
443
|
+
only_cross_attention=only_cross_attention,
|
444
|
+
upcast_attention=upcast_attention,
|
445
|
+
attention_type=attention_type,
|
446
|
+
)
|
447
|
+
)
|
448
|
+
else:
|
449
|
+
attentions.append(
|
450
|
+
DualTransformer2DModel(
|
451
|
+
num_attention_heads,
|
452
|
+
out_channels // num_attention_heads,
|
453
|
+
in_channels=out_channels,
|
454
|
+
num_layers=1,
|
455
|
+
cross_attention_dim=cross_attention_dim,
|
456
|
+
norm_num_groups=resnet_groups,
|
457
|
+
)
|
458
|
+
)
|
459
|
+
|
460
|
+
motion_modules.append(
|
461
|
+
AnimateDiffTransformer3D(
|
462
|
+
num_attention_heads=temporal_num_attention_heads,
|
463
|
+
in_channels=out_channels,
|
464
|
+
num_layers=temporal_transformer_layers_per_block[i],
|
465
|
+
norm_num_groups=resnet_groups,
|
466
|
+
cross_attention_dim=temporal_cross_attention_dim,
|
467
|
+
attention_bias=False,
|
468
|
+
activation_fn="geglu",
|
469
|
+
positional_embeddings="sinusoidal",
|
470
|
+
num_positional_embeddings=temporal_max_seq_length,
|
471
|
+
attention_head_dim=out_channels // temporal_num_attention_heads,
|
472
|
+
double_self_attention=temporal_double_self_attention,
|
473
|
+
)
|
474
|
+
)
|
475
|
+
|
476
|
+
self.attentions = nn.ModuleList(attentions)
|
477
|
+
self.resnets = nn.ModuleList(resnets)
|
478
|
+
self.motion_modules = nn.ModuleList(motion_modules)
|
479
|
+
|
480
|
+
if add_downsample:
|
481
|
+
self.downsamplers = nn.ModuleList(
|
482
|
+
[
|
483
|
+
Downsample2D(
|
484
|
+
out_channels,
|
485
|
+
use_conv=True,
|
486
|
+
out_channels=out_channels,
|
487
|
+
padding=downsample_padding,
|
488
|
+
name="op",
|
489
|
+
)
|
490
|
+
]
|
491
|
+
)
|
492
|
+
else:
|
493
|
+
self.downsamplers = None
|
494
|
+
|
495
|
+
self.gradient_checkpointing = False
|
496
|
+
|
497
|
+
def forward(
|
498
|
+
self,
|
499
|
+
hidden_states: torch.Tensor,
|
500
|
+
temb: Optional[torch.Tensor] = None,
|
501
|
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
502
|
+
attention_mask: Optional[torch.Tensor] = None,
|
503
|
+
num_frames: int = 1,
|
504
|
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
505
|
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
506
|
+
additional_residuals: Optional[torch.Tensor] = None,
|
507
|
+
):
|
508
|
+
if cross_attention_kwargs is not None:
|
509
|
+
if cross_attention_kwargs.get("scale", None) is not None:
|
510
|
+
logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
|
511
|
+
|
512
|
+
output_states = ()
|
513
|
+
|
514
|
+
blocks = list(zip(self.resnets, self.attentions, self.motion_modules))
|
515
|
+
for i, (resnet, attn, motion_module) in enumerate(blocks):
|
516
|
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
517
|
+
|
518
|
+
def create_custom_forward(module, return_dict=None):
|
519
|
+
def custom_forward(*inputs):
|
520
|
+
if return_dict is not None:
|
521
|
+
return module(*inputs, return_dict=return_dict)
|
522
|
+
else:
|
523
|
+
return module(*inputs)
|
524
|
+
|
525
|
+
return custom_forward
|
526
|
+
|
527
|
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
528
|
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
529
|
+
create_custom_forward(resnet),
|
530
|
+
hidden_states,
|
531
|
+
temb,
|
532
|
+
**ckpt_kwargs,
|
533
|
+
)
|
534
|
+
else:
|
535
|
+
hidden_states = resnet(input_tensor=hidden_states, temb=temb)
|
536
|
+
|
537
|
+
hidden_states = attn(
|
538
|
+
hidden_states=hidden_states,
|
539
|
+
encoder_hidden_states=encoder_hidden_states,
|
540
|
+
cross_attention_kwargs=cross_attention_kwargs,
|
541
|
+
attention_mask=attention_mask,
|
542
|
+
encoder_attention_mask=encoder_attention_mask,
|
543
|
+
return_dict=False,
|
544
|
+
)[0]
|
545
|
+
|
546
|
+
hidden_states = motion_module(
|
547
|
+
hidden_states,
|
548
|
+
num_frames=num_frames,
|
549
|
+
)
|
550
|
+
|
551
|
+
# apply additional residuals to the output of the last pair of resnet and attention blocks
|
552
|
+
if i == len(blocks) - 1 and additional_residuals is not None:
|
553
|
+
hidden_states = hidden_states + additional_residuals
|
554
|
+
|
555
|
+
output_states = output_states + (hidden_states,)
|
556
|
+
|
557
|
+
if self.downsamplers is not None:
|
558
|
+
for downsampler in self.downsamplers:
|
559
|
+
hidden_states = downsampler(hidden_states=hidden_states)
|
560
|
+
|
561
|
+
output_states = output_states + (hidden_states,)
|
562
|
+
|
563
|
+
return hidden_states, output_states
|
564
|
+
|
565
|
+
|
566
|
+
class CrossAttnUpBlockMotion(nn.Module):
|
567
|
+
def __init__(
|
568
|
+
self,
|
569
|
+
in_channels: int,
|
570
|
+
out_channels: int,
|
571
|
+
prev_output_channel: int,
|
572
|
+
temb_channels: int,
|
573
|
+
resolution_idx: Optional[int] = None,
|
574
|
+
dropout: float = 0.0,
|
575
|
+
num_layers: int = 1,
|
576
|
+
transformer_layers_per_block: Union[int, Tuple[int]] = 1,
|
577
|
+
resnet_eps: float = 1e-6,
|
578
|
+
resnet_time_scale_shift: str = "default",
|
579
|
+
resnet_act_fn: str = "swish",
|
580
|
+
resnet_groups: int = 32,
|
581
|
+
resnet_pre_norm: bool = True,
|
582
|
+
num_attention_heads: int = 1,
|
583
|
+
cross_attention_dim: int = 1280,
|
584
|
+
output_scale_factor: float = 1.0,
|
585
|
+
add_upsample: bool = True,
|
586
|
+
dual_cross_attention: bool = False,
|
587
|
+
use_linear_projection: bool = False,
|
588
|
+
only_cross_attention: bool = False,
|
589
|
+
upcast_attention: bool = False,
|
590
|
+
attention_type: str = "default",
|
591
|
+
temporal_cross_attention_dim: Optional[int] = None,
|
592
|
+
temporal_num_attention_heads: int = 8,
|
593
|
+
temporal_max_seq_length: int = 32,
|
594
|
+
temporal_transformer_layers_per_block: Union[int, Tuple[int]] = 1,
|
595
|
+
):
|
596
|
+
super().__init__()
|
597
|
+
resnets = []
|
598
|
+
attentions = []
|
599
|
+
motion_modules = []
|
600
|
+
|
601
|
+
self.has_cross_attention = True
|
602
|
+
self.num_attention_heads = num_attention_heads
|
603
|
+
|
604
|
+
# support for variable transformer layers per block
|
605
|
+
if isinstance(transformer_layers_per_block, int):
|
606
|
+
transformer_layers_per_block = (transformer_layers_per_block,) * num_layers
|
607
|
+
elif len(transformer_layers_per_block) != num_layers:
|
608
|
+
raise ValueError(
|
609
|
+
f"transformer_layers_per_block must be an integer or a list of integers of length {num_layers}, got {len(transformer_layers_per_block)}"
|
610
|
+
)
|
611
|
+
|
612
|
+
# support for variable transformer layers per temporal block
|
613
|
+
if isinstance(temporal_transformer_layers_per_block, int):
|
614
|
+
temporal_transformer_layers_per_block = (temporal_transformer_layers_per_block,) * num_layers
|
615
|
+
elif len(temporal_transformer_layers_per_block) != num_layers:
|
616
|
+
raise ValueError(
|
617
|
+
f"temporal_transformer_layers_per_block must be an integer or a list of integers of length {num_layers}, got {len(temporal_transformer_layers_per_block)}"
|
618
|
+
)
|
619
|
+
|
620
|
+
for i in range(num_layers):
|
621
|
+
res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
|
622
|
+
resnet_in_channels = prev_output_channel if i == 0 else out_channels
|
623
|
+
|
624
|
+
resnets.append(
|
625
|
+
ResnetBlock2D(
|
626
|
+
in_channels=resnet_in_channels + res_skip_channels,
|
627
|
+
out_channels=out_channels,
|
628
|
+
temb_channels=temb_channels,
|
629
|
+
eps=resnet_eps,
|
630
|
+
groups=resnet_groups,
|
631
|
+
dropout=dropout,
|
632
|
+
time_embedding_norm=resnet_time_scale_shift,
|
633
|
+
non_linearity=resnet_act_fn,
|
634
|
+
output_scale_factor=output_scale_factor,
|
635
|
+
pre_norm=resnet_pre_norm,
|
636
|
+
)
|
637
|
+
)
|
638
|
+
|
639
|
+
if not dual_cross_attention:
|
640
|
+
attentions.append(
|
641
|
+
Transformer2DModel(
|
642
|
+
num_attention_heads,
|
643
|
+
out_channels // num_attention_heads,
|
644
|
+
in_channels=out_channels,
|
645
|
+
num_layers=transformer_layers_per_block[i],
|
646
|
+
cross_attention_dim=cross_attention_dim,
|
647
|
+
norm_num_groups=resnet_groups,
|
648
|
+
use_linear_projection=use_linear_projection,
|
649
|
+
only_cross_attention=only_cross_attention,
|
650
|
+
upcast_attention=upcast_attention,
|
651
|
+
attention_type=attention_type,
|
652
|
+
)
|
653
|
+
)
|
654
|
+
else:
|
655
|
+
attentions.append(
|
656
|
+
DualTransformer2DModel(
|
657
|
+
num_attention_heads,
|
658
|
+
out_channels // num_attention_heads,
|
659
|
+
in_channels=out_channels,
|
660
|
+
num_layers=1,
|
661
|
+
cross_attention_dim=cross_attention_dim,
|
662
|
+
norm_num_groups=resnet_groups,
|
663
|
+
)
|
664
|
+
)
|
665
|
+
motion_modules.append(
|
666
|
+
AnimateDiffTransformer3D(
|
667
|
+
num_attention_heads=temporal_num_attention_heads,
|
668
|
+
in_channels=out_channels,
|
669
|
+
num_layers=temporal_transformer_layers_per_block[i],
|
670
|
+
norm_num_groups=resnet_groups,
|
671
|
+
cross_attention_dim=temporal_cross_attention_dim,
|
672
|
+
attention_bias=False,
|
673
|
+
activation_fn="geglu",
|
674
|
+
positional_embeddings="sinusoidal",
|
675
|
+
num_positional_embeddings=temporal_max_seq_length,
|
676
|
+
attention_head_dim=out_channels // temporal_num_attention_heads,
|
677
|
+
)
|
678
|
+
)
|
679
|
+
|
680
|
+
self.attentions = nn.ModuleList(attentions)
|
681
|
+
self.resnets = nn.ModuleList(resnets)
|
682
|
+
self.motion_modules = nn.ModuleList(motion_modules)
|
683
|
+
|
684
|
+
if add_upsample:
|
685
|
+
self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)])
|
686
|
+
else:
|
687
|
+
self.upsamplers = None
|
688
|
+
|
689
|
+
self.gradient_checkpointing = False
|
690
|
+
self.resolution_idx = resolution_idx
|
691
|
+
|
692
|
+
def forward(
|
693
|
+
self,
|
694
|
+
hidden_states: torch.Tensor,
|
695
|
+
res_hidden_states_tuple: Tuple[torch.Tensor, ...],
|
696
|
+
temb: Optional[torch.Tensor] = None,
|
697
|
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
698
|
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
699
|
+
upsample_size: Optional[int] = None,
|
700
|
+
attention_mask: Optional[torch.Tensor] = None,
|
701
|
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
702
|
+
num_frames: int = 1,
|
703
|
+
) -> torch.Tensor:
|
704
|
+
if cross_attention_kwargs is not None:
|
705
|
+
if cross_attention_kwargs.get("scale", None) is not None:
|
706
|
+
logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
|
707
|
+
|
708
|
+
is_freeu_enabled = (
|
709
|
+
getattr(self, "s1", None)
|
710
|
+
and getattr(self, "s2", None)
|
711
|
+
and getattr(self, "b1", None)
|
712
|
+
and getattr(self, "b2", None)
|
713
|
+
)
|
714
|
+
|
715
|
+
blocks = zip(self.resnets, self.attentions, self.motion_modules)
|
716
|
+
for resnet, attn, motion_module in blocks:
|
717
|
+
# pop res hidden states
|
718
|
+
res_hidden_states = res_hidden_states_tuple[-1]
|
719
|
+
res_hidden_states_tuple = res_hidden_states_tuple[:-1]
|
720
|
+
|
721
|
+
# FreeU: Only operate on the first two stages
|
722
|
+
if is_freeu_enabled:
|
723
|
+
hidden_states, res_hidden_states = apply_freeu(
|
724
|
+
self.resolution_idx,
|
725
|
+
hidden_states,
|
726
|
+
res_hidden_states,
|
727
|
+
s1=self.s1,
|
728
|
+
s2=self.s2,
|
729
|
+
b1=self.b1,
|
730
|
+
b2=self.b2,
|
731
|
+
)
|
732
|
+
|
733
|
+
hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
|
734
|
+
|
735
|
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
736
|
+
|
737
|
+
def create_custom_forward(module, return_dict=None):
|
738
|
+
def custom_forward(*inputs):
|
739
|
+
if return_dict is not None:
|
740
|
+
return module(*inputs, return_dict=return_dict)
|
741
|
+
else:
|
742
|
+
return module(*inputs)
|
743
|
+
|
744
|
+
return custom_forward
|
745
|
+
|
746
|
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
747
|
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
748
|
+
create_custom_forward(resnet),
|
749
|
+
hidden_states,
|
750
|
+
temb,
|
751
|
+
**ckpt_kwargs,
|
752
|
+
)
|
753
|
+
else:
|
754
|
+
hidden_states = resnet(input_tensor=hidden_states, temb=temb)
|
755
|
+
|
756
|
+
hidden_states = attn(
|
757
|
+
hidden_states=hidden_states,
|
758
|
+
encoder_hidden_states=encoder_hidden_states,
|
759
|
+
cross_attention_kwargs=cross_attention_kwargs,
|
760
|
+
attention_mask=attention_mask,
|
761
|
+
encoder_attention_mask=encoder_attention_mask,
|
762
|
+
return_dict=False,
|
763
|
+
)[0]
|
764
|
+
|
765
|
+
hidden_states = motion_module(
|
766
|
+
hidden_states,
|
767
|
+
num_frames=num_frames,
|
768
|
+
)
|
769
|
+
|
770
|
+
if self.upsamplers is not None:
|
771
|
+
for upsampler in self.upsamplers:
|
772
|
+
hidden_states = upsampler(hidden_states=hidden_states, output_size=upsample_size)
|
773
|
+
|
774
|
+
return hidden_states
|
775
|
+
|
776
|
+
|
777
|
+
class UpBlockMotion(nn.Module):
|
778
|
+
def __init__(
|
779
|
+
self,
|
780
|
+
in_channels: int,
|
781
|
+
prev_output_channel: int,
|
782
|
+
out_channels: int,
|
783
|
+
temb_channels: int,
|
784
|
+
resolution_idx: Optional[int] = None,
|
785
|
+
dropout: float = 0.0,
|
786
|
+
num_layers: int = 1,
|
787
|
+
resnet_eps: float = 1e-6,
|
788
|
+
resnet_time_scale_shift: str = "default",
|
789
|
+
resnet_act_fn: str = "swish",
|
790
|
+
resnet_groups: int = 32,
|
791
|
+
resnet_pre_norm: bool = True,
|
792
|
+
output_scale_factor: float = 1.0,
|
793
|
+
add_upsample: bool = True,
|
794
|
+
temporal_cross_attention_dim: Optional[int] = None,
|
795
|
+
temporal_num_attention_heads: int = 8,
|
796
|
+
temporal_max_seq_length: int = 32,
|
797
|
+
temporal_transformer_layers_per_block: Union[int, Tuple[int]] = 1,
|
798
|
+
):
|
799
|
+
super().__init__()
|
800
|
+
resnets = []
|
801
|
+
motion_modules = []
|
802
|
+
|
803
|
+
# support for variable transformer layers per temporal block
|
804
|
+
if isinstance(temporal_transformer_layers_per_block, int):
|
805
|
+
temporal_transformer_layers_per_block = (temporal_transformer_layers_per_block,) * num_layers
|
806
|
+
elif len(temporal_transformer_layers_per_block) != num_layers:
|
807
|
+
raise ValueError(
|
808
|
+
f"temporal_transformer_layers_per_block must be an integer or a list of integers of length {num_layers}"
|
809
|
+
)
|
810
|
+
|
811
|
+
for i in range(num_layers):
|
812
|
+
res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
|
813
|
+
resnet_in_channels = prev_output_channel if i == 0 else out_channels
|
814
|
+
|
815
|
+
resnets.append(
|
816
|
+
ResnetBlock2D(
|
817
|
+
in_channels=resnet_in_channels + res_skip_channels,
|
818
|
+
out_channels=out_channels,
|
819
|
+
temb_channels=temb_channels,
|
820
|
+
eps=resnet_eps,
|
821
|
+
groups=resnet_groups,
|
822
|
+
dropout=dropout,
|
823
|
+
time_embedding_norm=resnet_time_scale_shift,
|
824
|
+
non_linearity=resnet_act_fn,
|
825
|
+
output_scale_factor=output_scale_factor,
|
826
|
+
pre_norm=resnet_pre_norm,
|
827
|
+
)
|
828
|
+
)
|
829
|
+
|
830
|
+
motion_modules.append(
|
831
|
+
AnimateDiffTransformer3D(
|
832
|
+
num_attention_heads=temporal_num_attention_heads,
|
833
|
+
in_channels=out_channels,
|
834
|
+
num_layers=temporal_transformer_layers_per_block[i],
|
835
|
+
norm_num_groups=resnet_groups,
|
836
|
+
cross_attention_dim=temporal_cross_attention_dim,
|
837
|
+
attention_bias=False,
|
838
|
+
activation_fn="geglu",
|
839
|
+
positional_embeddings="sinusoidal",
|
840
|
+
num_positional_embeddings=temporal_max_seq_length,
|
841
|
+
attention_head_dim=out_channels // temporal_num_attention_heads,
|
842
|
+
)
|
843
|
+
)
|
844
|
+
|
845
|
+
self.resnets = nn.ModuleList(resnets)
|
846
|
+
self.motion_modules = nn.ModuleList(motion_modules)
|
847
|
+
|
848
|
+
if add_upsample:
|
849
|
+
self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)])
|
850
|
+
else:
|
851
|
+
self.upsamplers = None
|
852
|
+
|
853
|
+
self.gradient_checkpointing = False
|
854
|
+
self.resolution_idx = resolution_idx
|
855
|
+
|
856
|
+
def forward(
|
857
|
+
self,
|
858
|
+
hidden_states: torch.Tensor,
|
859
|
+
res_hidden_states_tuple: Tuple[torch.Tensor, ...],
|
860
|
+
temb: Optional[torch.Tensor] = None,
|
861
|
+
upsample_size=None,
|
862
|
+
num_frames: int = 1,
|
863
|
+
*args,
|
864
|
+
**kwargs,
|
865
|
+
) -> torch.Tensor:
|
866
|
+
if len(args) > 0 or kwargs.get("scale", None) is not None:
|
867
|
+
deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
|
868
|
+
deprecate("scale", "1.0.0", deprecation_message)
|
869
|
+
|
870
|
+
is_freeu_enabled = (
|
871
|
+
getattr(self, "s1", None)
|
872
|
+
and getattr(self, "s2", None)
|
873
|
+
and getattr(self, "b1", None)
|
874
|
+
and getattr(self, "b2", None)
|
875
|
+
)
|
876
|
+
|
877
|
+
blocks = zip(self.resnets, self.motion_modules)
|
878
|
+
|
879
|
+
for resnet, motion_module in blocks:
|
880
|
+
# pop res hidden states
|
881
|
+
res_hidden_states = res_hidden_states_tuple[-1]
|
882
|
+
res_hidden_states_tuple = res_hidden_states_tuple[:-1]
|
883
|
+
|
884
|
+
# FreeU: Only operate on the first two stages
|
885
|
+
if is_freeu_enabled:
|
886
|
+
hidden_states, res_hidden_states = apply_freeu(
|
887
|
+
self.resolution_idx,
|
888
|
+
hidden_states,
|
889
|
+
res_hidden_states,
|
890
|
+
s1=self.s1,
|
891
|
+
s2=self.s2,
|
892
|
+
b1=self.b1,
|
893
|
+
b2=self.b2,
|
894
|
+
)
|
895
|
+
|
896
|
+
hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
|
897
|
+
|
898
|
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
899
|
+
|
900
|
+
def create_custom_forward(module):
|
901
|
+
def custom_forward(*inputs):
|
902
|
+
return module(*inputs)
|
903
|
+
|
904
|
+
return custom_forward
|
905
|
+
|
906
|
+
if is_torch_version(">=", "1.11.0"):
|
907
|
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
908
|
+
create_custom_forward(resnet),
|
909
|
+
hidden_states,
|
910
|
+
temb,
|
911
|
+
use_reentrant=False,
|
912
|
+
)
|
913
|
+
else:
|
914
|
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
915
|
+
create_custom_forward(resnet), hidden_states, temb
|
916
|
+
)
|
917
|
+
else:
|
918
|
+
hidden_states = resnet(input_tensor=hidden_states, temb=temb)
|
919
|
+
|
920
|
+
hidden_states = motion_module(hidden_states, num_frames=num_frames)
|
921
|
+
|
922
|
+
if self.upsamplers is not None:
|
923
|
+
for upsampler in self.upsamplers:
|
924
|
+
hidden_states = upsampler(hidden_states=hidden_states, output_size=upsample_size)
|
925
|
+
|
926
|
+
return hidden_states
|
927
|
+
|
928
|
+
|
929
|
+
class UNetMidBlockCrossAttnMotion(nn.Module):
|
930
|
+
def __init__(
|
931
|
+
self,
|
932
|
+
in_channels: int,
|
933
|
+
temb_channels: int,
|
934
|
+
dropout: float = 0.0,
|
935
|
+
num_layers: int = 1,
|
936
|
+
transformer_layers_per_block: Union[int, Tuple[int]] = 1,
|
937
|
+
resnet_eps: float = 1e-6,
|
938
|
+
resnet_time_scale_shift: str = "default",
|
939
|
+
resnet_act_fn: str = "swish",
|
940
|
+
resnet_groups: int = 32,
|
941
|
+
resnet_pre_norm: bool = True,
|
942
|
+
num_attention_heads: int = 1,
|
943
|
+
output_scale_factor: float = 1.0,
|
944
|
+
cross_attention_dim: int = 1280,
|
945
|
+
dual_cross_attention: bool = False,
|
946
|
+
use_linear_projection: bool = False,
|
947
|
+
upcast_attention: bool = False,
|
948
|
+
attention_type: str = "default",
|
949
|
+
temporal_num_attention_heads: int = 1,
|
950
|
+
temporal_cross_attention_dim: Optional[int] = None,
|
951
|
+
temporal_max_seq_length: int = 32,
|
952
|
+
temporal_transformer_layers_per_block: Union[int, Tuple[int]] = 1,
|
953
|
+
):
|
954
|
+
super().__init__()
|
955
|
+
|
956
|
+
self.has_cross_attention = True
|
957
|
+
self.num_attention_heads = num_attention_heads
|
958
|
+
resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
|
959
|
+
|
960
|
+
# support for variable transformer layers per block
|
961
|
+
if isinstance(transformer_layers_per_block, int):
|
962
|
+
transformer_layers_per_block = (transformer_layers_per_block,) * num_layers
|
963
|
+
elif len(transformer_layers_per_block) != num_layers:
|
964
|
+
raise ValueError(
|
965
|
+
f"`transformer_layers_per_block` should be an integer or a list of integers of length {num_layers}."
|
966
|
+
)
|
967
|
+
|
968
|
+
# support for variable transformer layers per temporal block
|
969
|
+
if isinstance(temporal_transformer_layers_per_block, int):
|
970
|
+
temporal_transformer_layers_per_block = (temporal_transformer_layers_per_block,) * num_layers
|
971
|
+
elif len(temporal_transformer_layers_per_block) != num_layers:
|
972
|
+
raise ValueError(
|
973
|
+
f"`temporal_transformer_layers_per_block` should be an integer or a list of integers of length {num_layers}."
|
974
|
+
)
|
975
|
+
|
976
|
+
# there is always at least one resnet
|
977
|
+
resnets = [
|
978
|
+
ResnetBlock2D(
|
979
|
+
in_channels=in_channels,
|
980
|
+
out_channels=in_channels,
|
981
|
+
temb_channels=temb_channels,
|
982
|
+
eps=resnet_eps,
|
983
|
+
groups=resnet_groups,
|
984
|
+
dropout=dropout,
|
985
|
+
time_embedding_norm=resnet_time_scale_shift,
|
986
|
+
non_linearity=resnet_act_fn,
|
987
|
+
output_scale_factor=output_scale_factor,
|
988
|
+
pre_norm=resnet_pre_norm,
|
989
|
+
)
|
990
|
+
]
|
991
|
+
attentions = []
|
992
|
+
motion_modules = []
|
993
|
+
|
994
|
+
for i in range(num_layers):
|
995
|
+
if not dual_cross_attention:
|
996
|
+
attentions.append(
|
997
|
+
Transformer2DModel(
|
998
|
+
num_attention_heads,
|
999
|
+
in_channels // num_attention_heads,
|
1000
|
+
in_channels=in_channels,
|
1001
|
+
num_layers=transformer_layers_per_block[i],
|
1002
|
+
cross_attention_dim=cross_attention_dim,
|
1003
|
+
norm_num_groups=resnet_groups,
|
1004
|
+
use_linear_projection=use_linear_projection,
|
1005
|
+
upcast_attention=upcast_attention,
|
1006
|
+
attention_type=attention_type,
|
1007
|
+
)
|
1008
|
+
)
|
1009
|
+
else:
|
1010
|
+
attentions.append(
|
1011
|
+
DualTransformer2DModel(
|
1012
|
+
num_attention_heads,
|
1013
|
+
in_channels // num_attention_heads,
|
1014
|
+
in_channels=in_channels,
|
1015
|
+
num_layers=1,
|
1016
|
+
cross_attention_dim=cross_attention_dim,
|
1017
|
+
norm_num_groups=resnet_groups,
|
1018
|
+
)
|
1019
|
+
)
|
1020
|
+
resnets.append(
|
1021
|
+
ResnetBlock2D(
|
1022
|
+
in_channels=in_channels,
|
1023
|
+
out_channels=in_channels,
|
1024
|
+
temb_channels=temb_channels,
|
1025
|
+
eps=resnet_eps,
|
1026
|
+
groups=resnet_groups,
|
1027
|
+
dropout=dropout,
|
1028
|
+
time_embedding_norm=resnet_time_scale_shift,
|
1029
|
+
non_linearity=resnet_act_fn,
|
1030
|
+
output_scale_factor=output_scale_factor,
|
1031
|
+
pre_norm=resnet_pre_norm,
|
1032
|
+
)
|
1033
|
+
)
|
1034
|
+
motion_modules.append(
|
1035
|
+
AnimateDiffTransformer3D(
|
1036
|
+
num_attention_heads=temporal_num_attention_heads,
|
1037
|
+
attention_head_dim=in_channels // temporal_num_attention_heads,
|
1038
|
+
in_channels=in_channels,
|
1039
|
+
num_layers=temporal_transformer_layers_per_block[i],
|
1040
|
+
norm_num_groups=resnet_groups,
|
1041
|
+
cross_attention_dim=temporal_cross_attention_dim,
|
1042
|
+
attention_bias=False,
|
1043
|
+
positional_embeddings="sinusoidal",
|
1044
|
+
num_positional_embeddings=temporal_max_seq_length,
|
1045
|
+
activation_fn="geglu",
|
1046
|
+
)
|
1047
|
+
)
|
1048
|
+
|
1049
|
+
self.attentions = nn.ModuleList(attentions)
|
1050
|
+
self.resnets = nn.ModuleList(resnets)
|
1051
|
+
self.motion_modules = nn.ModuleList(motion_modules)
|
1052
|
+
|
1053
|
+
self.gradient_checkpointing = False
|
1054
|
+
|
1055
|
+
def forward(
|
1056
|
+
self,
|
1057
|
+
hidden_states: torch.Tensor,
|
1058
|
+
temb: Optional[torch.Tensor] = None,
|
1059
|
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
1060
|
+
attention_mask: Optional[torch.Tensor] = None,
|
1061
|
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
1062
|
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
1063
|
+
num_frames: int = 1,
|
1064
|
+
) -> torch.Tensor:
|
1065
|
+
if cross_attention_kwargs is not None:
|
1066
|
+
if cross_attention_kwargs.get("scale", None) is not None:
|
1067
|
+
logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
|
1068
|
+
|
1069
|
+
hidden_states = self.resnets[0](input_tensor=hidden_states, temb=temb)
|
1070
|
+
|
1071
|
+
blocks = zip(self.attentions, self.resnets[1:], self.motion_modules)
|
1072
|
+
for attn, resnet, motion_module in blocks:
|
1073
|
+
hidden_states = attn(
|
1074
|
+
hidden_states=hidden_states,
|
1075
|
+
encoder_hidden_states=encoder_hidden_states,
|
1076
|
+
cross_attention_kwargs=cross_attention_kwargs,
|
1077
|
+
attention_mask=attention_mask,
|
1078
|
+
encoder_attention_mask=encoder_attention_mask,
|
1079
|
+
return_dict=False,
|
1080
|
+
)[0]
|
1081
|
+
|
1082
|
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
1083
|
+
|
1084
|
+
def create_custom_forward(module, return_dict=None):
|
1085
|
+
def custom_forward(*inputs):
|
1086
|
+
if return_dict is not None:
|
1087
|
+
return module(*inputs, return_dict=return_dict)
|
1088
|
+
else:
|
1089
|
+
return module(*inputs)
|
1090
|
+
|
1091
|
+
return custom_forward
|
1092
|
+
|
1093
|
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
1094
|
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
1095
|
+
create_custom_forward(motion_module),
|
1096
|
+
hidden_states,
|
1097
|
+
temb,
|
1098
|
+
**ckpt_kwargs,
|
1099
|
+
)
|
1100
|
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
1101
|
+
create_custom_forward(resnet),
|
1102
|
+
hidden_states,
|
1103
|
+
temb,
|
1104
|
+
**ckpt_kwargs,
|
1105
|
+
)
|
1106
|
+
else:
|
1107
|
+
hidden_states = motion_module(
|
1108
|
+
hidden_states,
|
1109
|
+
num_frames=num_frames,
|
1110
|
+
)
|
1111
|
+
hidden_states = resnet(input_tensor=hidden_states, temb=temb)
|
1112
|
+
|
1113
|
+
return hidden_states
|
1114
|
+
|
1115
|
+
|
51
1116
|
class MotionModules(nn.Module):
|
52
1117
|
def __init__(
|
53
1118
|
self,
|
54
1119
|
in_channels: int,
|
55
1120
|
layers_per_block: int = 2,
|
56
|
-
|
1121
|
+
transformer_layers_per_block: Union[int, Tuple[int]] = 8,
|
1122
|
+
num_attention_heads: Union[int, Tuple[int]] = 8,
|
57
1123
|
attention_bias: bool = False,
|
58
1124
|
cross_attention_dim: Optional[int] = None,
|
59
1125
|
activation_fn: str = "geglu",
|
@@ -63,10 +1129,19 @@ class MotionModules(nn.Module):
|
|
63
1129
|
super().__init__()
|
64
1130
|
self.motion_modules = nn.ModuleList([])
|
65
1131
|
|
1132
|
+
if isinstance(transformer_layers_per_block, int):
|
1133
|
+
transformer_layers_per_block = (transformer_layers_per_block,) * layers_per_block
|
1134
|
+
elif len(transformer_layers_per_block) != layers_per_block:
|
1135
|
+
raise ValueError(
|
1136
|
+
f"The number of transformer layers per block must match the number of layers per block, "
|
1137
|
+
f"got {layers_per_block} and {len(transformer_layers_per_block)}"
|
1138
|
+
)
|
1139
|
+
|
66
1140
|
for i in range(layers_per_block):
|
67
1141
|
self.motion_modules.append(
|
68
|
-
|
1142
|
+
AnimateDiffTransformer3D(
|
69
1143
|
in_channels=in_channels,
|
1144
|
+
num_layers=transformer_layers_per_block[i],
|
70
1145
|
norm_num_groups=norm_num_groups,
|
71
1146
|
cross_attention_dim=cross_attention_dim,
|
72
1147
|
activation_fn=activation_fn,
|
@@ -79,14 +1154,16 @@ class MotionModules(nn.Module):
|
|
79
1154
|
)
|
80
1155
|
|
81
1156
|
|
82
|
-
class MotionAdapter(ModelMixin, ConfigMixin):
|
1157
|
+
class MotionAdapter(ModelMixin, ConfigMixin, FromOriginalModelMixin):
|
83
1158
|
@register_to_config
|
84
1159
|
def __init__(
|
85
1160
|
self,
|
86
1161
|
block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280),
|
87
|
-
motion_layers_per_block: int = 2,
|
1162
|
+
motion_layers_per_block: Union[int, Tuple[int]] = 2,
|
1163
|
+
motion_transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple[int]]] = 1,
|
88
1164
|
motion_mid_block_layers_per_block: int = 1,
|
89
|
-
|
1165
|
+
motion_transformer_layers_per_mid_block: Union[int, Tuple[int]] = 1,
|
1166
|
+
motion_num_attention_heads: Union[int, Tuple[int]] = 8,
|
90
1167
|
motion_norm_num_groups: int = 32,
|
91
1168
|
motion_max_seq_length: int = 32,
|
92
1169
|
use_motion_mid_block: bool = True,
|
@@ -97,11 +1174,15 @@ class MotionAdapter(ModelMixin, ConfigMixin):
|
|
97
1174
|
Args:
|
98
1175
|
block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
|
99
1176
|
The tuple of output channels for each UNet block.
|
100
|
-
motion_layers_per_block (`int`, *optional*, defaults to 2):
|
1177
|
+
motion_layers_per_block (`int` or `Tuple[int]`, *optional*, defaults to 2):
|
101
1178
|
The number of motion layers per UNet block.
|
1179
|
+
motion_transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple[int]]`, *optional*, defaults to 1):
|
1180
|
+
The number of transformer layers to use in each motion layer in each block.
|
102
1181
|
motion_mid_block_layers_per_block (`int`, *optional*, defaults to 1):
|
103
1182
|
The number of motion layers in the middle UNet block.
|
104
|
-
|
1183
|
+
motion_transformer_layers_per_mid_block (`int` or `Tuple[int]`, *optional*, defaults to 1):
|
1184
|
+
The number of transformer layers to use in each motion layer in the middle block.
|
1185
|
+
motion_num_attention_heads (`int` or `Tuple[int]`, *optional*, defaults to 8):
|
105
1186
|
The number of heads to use in each attention layer of the motion module.
|
106
1187
|
motion_norm_num_groups (`int`, *optional*, defaults to 32):
|
107
1188
|
The number of groups to use in each group normalization layer of the motion module.
|
@@ -115,6 +1196,35 @@ class MotionAdapter(ModelMixin, ConfigMixin):
|
|
115
1196
|
down_blocks = []
|
116
1197
|
up_blocks = []
|
117
1198
|
|
1199
|
+
if isinstance(motion_layers_per_block, int):
|
1200
|
+
motion_layers_per_block = (motion_layers_per_block,) * len(block_out_channels)
|
1201
|
+
elif len(motion_layers_per_block) != len(block_out_channels):
|
1202
|
+
raise ValueError(
|
1203
|
+
f"The number of motion layers per block must match the number of blocks, "
|
1204
|
+
f"got {len(block_out_channels)} and {len(motion_layers_per_block)}"
|
1205
|
+
)
|
1206
|
+
|
1207
|
+
if isinstance(motion_transformer_layers_per_block, int):
|
1208
|
+
motion_transformer_layers_per_block = (motion_transformer_layers_per_block,) * len(block_out_channels)
|
1209
|
+
|
1210
|
+
if isinstance(motion_transformer_layers_per_mid_block, int):
|
1211
|
+
motion_transformer_layers_per_mid_block = (
|
1212
|
+
motion_transformer_layers_per_mid_block,
|
1213
|
+
) * motion_mid_block_layers_per_block
|
1214
|
+
elif len(motion_transformer_layers_per_mid_block) != motion_mid_block_layers_per_block:
|
1215
|
+
raise ValueError(
|
1216
|
+
f"The number of layers per mid block ({motion_mid_block_layers_per_block}) "
|
1217
|
+
f"must match the length of motion_transformer_layers_per_mid_block ({len(motion_transformer_layers_per_mid_block)})"
|
1218
|
+
)
|
1219
|
+
|
1220
|
+
if isinstance(motion_num_attention_heads, int):
|
1221
|
+
motion_num_attention_heads = (motion_num_attention_heads,) * len(block_out_channels)
|
1222
|
+
elif len(motion_num_attention_heads) != len(block_out_channels):
|
1223
|
+
raise ValueError(
|
1224
|
+
f"The length of the attention head number tuple in the motion module must match the "
|
1225
|
+
f"number of block, got {len(motion_num_attention_heads)} and {len(block_out_channels)}"
|
1226
|
+
)
|
1227
|
+
|
118
1228
|
if conv_in_channels:
|
119
1229
|
# input
|
120
1230
|
self.conv_in = nn.Conv2d(conv_in_channels, block_out_channels[0], kernel_size=3, padding=1)
|
@@ -130,9 +1240,10 @@ class MotionAdapter(ModelMixin, ConfigMixin):
|
|
130
1240
|
cross_attention_dim=None,
|
131
1241
|
activation_fn="geglu",
|
132
1242
|
attention_bias=False,
|
133
|
-
num_attention_heads=motion_num_attention_heads,
|
1243
|
+
num_attention_heads=motion_num_attention_heads[i],
|
134
1244
|
max_seq_length=motion_max_seq_length,
|
135
|
-
layers_per_block=motion_layers_per_block,
|
1245
|
+
layers_per_block=motion_layers_per_block[i],
|
1246
|
+
transformer_layers_per_block=motion_transformer_layers_per_block[i],
|
136
1247
|
)
|
137
1248
|
)
|
138
1249
|
|
@@ -143,15 +1254,20 @@ class MotionAdapter(ModelMixin, ConfigMixin):
|
|
143
1254
|
cross_attention_dim=None,
|
144
1255
|
activation_fn="geglu",
|
145
1256
|
attention_bias=False,
|
146
|
-
num_attention_heads=motion_num_attention_heads,
|
147
|
-
layers_per_block=motion_mid_block_layers_per_block,
|
1257
|
+
num_attention_heads=motion_num_attention_heads[-1],
|
148
1258
|
max_seq_length=motion_max_seq_length,
|
1259
|
+
layers_per_block=motion_mid_block_layers_per_block,
|
1260
|
+
transformer_layers_per_block=motion_transformer_layers_per_mid_block,
|
149
1261
|
)
|
150
1262
|
else:
|
151
1263
|
self.mid_block = None
|
152
1264
|
|
153
1265
|
reversed_block_out_channels = list(reversed(block_out_channels))
|
154
1266
|
output_channel = reversed_block_out_channels[0]
|
1267
|
+
|
1268
|
+
reversed_motion_layers_per_block = list(reversed(motion_layers_per_block))
|
1269
|
+
reversed_motion_transformer_layers_per_block = list(reversed(motion_transformer_layers_per_block))
|
1270
|
+
reversed_motion_num_attention_heads = list(reversed(motion_num_attention_heads))
|
155
1271
|
for i, channel in enumerate(reversed_block_out_channels):
|
156
1272
|
output_channel = reversed_block_out_channels[i]
|
157
1273
|
up_blocks.append(
|
@@ -161,9 +1277,10 @@ class MotionAdapter(ModelMixin, ConfigMixin):
|
|
161
1277
|
cross_attention_dim=None,
|
162
1278
|
activation_fn="geglu",
|
163
1279
|
attention_bias=False,
|
164
|
-
num_attention_heads=
|
1280
|
+
num_attention_heads=reversed_motion_num_attention_heads[i],
|
165
1281
|
max_seq_length=motion_max_seq_length,
|
166
|
-
layers_per_block=
|
1282
|
+
layers_per_block=reversed_motion_layers_per_block[i] + 1,
|
1283
|
+
transformer_layers_per_block=reversed_motion_transformer_layers_per_block[i],
|
167
1284
|
)
|
168
1285
|
)
|
169
1286
|
|
@@ -174,7 +1291,7 @@ class MotionAdapter(ModelMixin, ConfigMixin):
|
|
174
1291
|
pass
|
175
1292
|
|
176
1293
|
|
177
|
-
class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
1294
|
+
class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin, PeftAdapterMixin):
|
178
1295
|
r"""
|
179
1296
|
A modified conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a
|
180
1297
|
sample shaped output.
|
@@ -204,20 +1321,31 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
204
1321
|
"CrossAttnUpBlockMotion",
|
205
1322
|
),
|
206
1323
|
block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280),
|
207
|
-
layers_per_block: int = 2,
|
1324
|
+
layers_per_block: Union[int, Tuple[int]] = 2,
|
208
1325
|
downsample_padding: int = 1,
|
209
1326
|
mid_block_scale_factor: float = 1,
|
210
1327
|
act_fn: str = "silu",
|
211
1328
|
norm_num_groups: int = 32,
|
212
1329
|
norm_eps: float = 1e-5,
|
213
1330
|
cross_attention_dim: int = 1280,
|
1331
|
+
transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
|
1332
|
+
reverse_transformer_layers_per_block: Optional[Union[int, Tuple[int], Tuple[Tuple]]] = None,
|
1333
|
+
temporal_transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
|
1334
|
+
reverse_temporal_transformer_layers_per_block: Optional[Union[int, Tuple[int], Tuple[Tuple]]] = None,
|
1335
|
+
transformer_layers_per_mid_block: Optional[Union[int, Tuple[int]]] = None,
|
1336
|
+
temporal_transformer_layers_per_mid_block: Optional[Union[int, Tuple[int]]] = 1,
|
214
1337
|
use_linear_projection: bool = False,
|
215
1338
|
num_attention_heads: Union[int, Tuple[int, ...]] = 8,
|
216
1339
|
motion_max_seq_length: int = 32,
|
217
|
-
motion_num_attention_heads: int = 8,
|
218
|
-
|
1340
|
+
motion_num_attention_heads: Union[int, Tuple[int, ...]] = 8,
|
1341
|
+
reverse_motion_num_attention_heads: Optional[Union[int, Tuple[int, ...], Tuple[Tuple[int, ...], ...]]] = None,
|
1342
|
+
use_motion_mid_block: bool = True,
|
1343
|
+
mid_block_layers: int = 1,
|
219
1344
|
encoder_hid_dim: Optional[int] = None,
|
220
1345
|
encoder_hid_dim_type: Optional[str] = None,
|
1346
|
+
addition_embed_type: Optional[str] = None,
|
1347
|
+
addition_time_embed_dim: Optional[int] = None,
|
1348
|
+
projection_class_embeddings_input_dim: Optional[int] = None,
|
221
1349
|
time_cond_proj_dim: Optional[int] = None,
|
222
1350
|
):
|
223
1351
|
super().__init__()
|
@@ -240,6 +1368,31 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
240
1368
|
f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}."
|
241
1369
|
)
|
242
1370
|
|
1371
|
+
if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types):
|
1372
|
+
raise ValueError(
|
1373
|
+
f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}."
|
1374
|
+
)
|
1375
|
+
|
1376
|
+
if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types):
|
1377
|
+
raise ValueError(
|
1378
|
+
f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}."
|
1379
|
+
)
|
1380
|
+
|
1381
|
+
if isinstance(transformer_layers_per_block, list) and reverse_transformer_layers_per_block is None:
|
1382
|
+
for layer_number_per_block in transformer_layers_per_block:
|
1383
|
+
if isinstance(layer_number_per_block, list):
|
1384
|
+
raise ValueError("Must provide 'reverse_transformer_layers_per_block` if using asymmetrical UNet.")
|
1385
|
+
|
1386
|
+
if (
|
1387
|
+
isinstance(temporal_transformer_layers_per_block, list)
|
1388
|
+
and reverse_temporal_transformer_layers_per_block is None
|
1389
|
+
):
|
1390
|
+
for layer_number_per_block in temporal_transformer_layers_per_block:
|
1391
|
+
if isinstance(layer_number_per_block, list):
|
1392
|
+
raise ValueError(
|
1393
|
+
"Must provide 'reverse_temporal_transformer_layers_per_block` if using asymmetrical motion module in UNet."
|
1394
|
+
)
|
1395
|
+
|
243
1396
|
# input
|
244
1397
|
conv_in_kernel = 3
|
245
1398
|
conv_out_kernel = 3
|
@@ -260,6 +1413,10 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
260
1413
|
if encoder_hid_dim_type is None:
|
261
1414
|
self.encoder_hid_proj = None
|
262
1415
|
|
1416
|
+
if addition_embed_type == "text_time":
|
1417
|
+
self.add_time_proj = Timesteps(addition_time_embed_dim, True, 0)
|
1418
|
+
self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
|
1419
|
+
|
263
1420
|
# class embedding
|
264
1421
|
self.down_blocks = nn.ModuleList([])
|
265
1422
|
self.up_blocks = nn.ModuleList([])
|
@@ -267,6 +1424,29 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
267
1424
|
if isinstance(num_attention_heads, int):
|
268
1425
|
num_attention_heads = (num_attention_heads,) * len(down_block_types)
|
269
1426
|
|
1427
|
+
if isinstance(cross_attention_dim, int):
|
1428
|
+
cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
|
1429
|
+
|
1430
|
+
if isinstance(layers_per_block, int):
|
1431
|
+
layers_per_block = [layers_per_block] * len(down_block_types)
|
1432
|
+
|
1433
|
+
if isinstance(transformer_layers_per_block, int):
|
1434
|
+
transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
|
1435
|
+
|
1436
|
+
if isinstance(reverse_transformer_layers_per_block, int):
|
1437
|
+
reverse_transformer_layers_per_block = [reverse_transformer_layers_per_block] * len(down_block_types)
|
1438
|
+
|
1439
|
+
if isinstance(temporal_transformer_layers_per_block, int):
|
1440
|
+
temporal_transformer_layers_per_block = [temporal_transformer_layers_per_block] * len(down_block_types)
|
1441
|
+
|
1442
|
+
if isinstance(reverse_temporal_transformer_layers_per_block, int):
|
1443
|
+
reverse_temporal_transformer_layers_per_block = [reverse_temporal_transformer_layers_per_block] * len(
|
1444
|
+
down_block_types
|
1445
|
+
)
|
1446
|
+
|
1447
|
+
if isinstance(motion_num_attention_heads, int):
|
1448
|
+
motion_num_attention_heads = (motion_num_attention_heads,) * len(down_block_types)
|
1449
|
+
|
270
1450
|
# down
|
271
1451
|
output_channel = block_out_channels[0]
|
272
1452
|
for i, down_block_type in enumerate(down_block_types):
|
@@ -274,27 +1454,53 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
274
1454
|
output_channel = block_out_channels[i]
|
275
1455
|
is_final_block = i == len(block_out_channels) - 1
|
276
1456
|
|
277
|
-
|
278
|
-
|
279
|
-
|
280
|
-
|
281
|
-
|
282
|
-
|
283
|
-
|
284
|
-
|
285
|
-
|
286
|
-
|
287
|
-
|
288
|
-
|
289
|
-
|
290
|
-
|
291
|
-
|
292
|
-
|
293
|
-
|
294
|
-
|
1457
|
+
if down_block_type == "CrossAttnDownBlockMotion":
|
1458
|
+
down_block = CrossAttnDownBlockMotion(
|
1459
|
+
in_channels=input_channel,
|
1460
|
+
out_channels=output_channel,
|
1461
|
+
temb_channels=time_embed_dim,
|
1462
|
+
num_layers=layers_per_block[i],
|
1463
|
+
transformer_layers_per_block=transformer_layers_per_block[i],
|
1464
|
+
resnet_eps=norm_eps,
|
1465
|
+
resnet_act_fn=act_fn,
|
1466
|
+
resnet_groups=norm_num_groups,
|
1467
|
+
num_attention_heads=num_attention_heads[i],
|
1468
|
+
cross_attention_dim=cross_attention_dim[i],
|
1469
|
+
downsample_padding=downsample_padding,
|
1470
|
+
add_downsample=not is_final_block,
|
1471
|
+
use_linear_projection=use_linear_projection,
|
1472
|
+
temporal_num_attention_heads=motion_num_attention_heads[i],
|
1473
|
+
temporal_max_seq_length=motion_max_seq_length,
|
1474
|
+
temporal_transformer_layers_per_block=temporal_transformer_layers_per_block[i],
|
1475
|
+
)
|
1476
|
+
elif down_block_type == "DownBlockMotion":
|
1477
|
+
down_block = DownBlockMotion(
|
1478
|
+
in_channels=input_channel,
|
1479
|
+
out_channels=output_channel,
|
1480
|
+
temb_channels=time_embed_dim,
|
1481
|
+
num_layers=layers_per_block[i],
|
1482
|
+
resnet_eps=norm_eps,
|
1483
|
+
resnet_act_fn=act_fn,
|
1484
|
+
resnet_groups=norm_num_groups,
|
1485
|
+
add_downsample=not is_final_block,
|
1486
|
+
downsample_padding=downsample_padding,
|
1487
|
+
temporal_num_attention_heads=motion_num_attention_heads[i],
|
1488
|
+
temporal_max_seq_length=motion_max_seq_length,
|
1489
|
+
temporal_transformer_layers_per_block=temporal_transformer_layers_per_block[i],
|
1490
|
+
)
|
1491
|
+
else:
|
1492
|
+
raise ValueError(
|
1493
|
+
"Invalid `down_block_type` encountered. Must be one of `CrossAttnDownBlockMotion` or `DownBlockMotion`"
|
1494
|
+
)
|
1495
|
+
|
295
1496
|
self.down_blocks.append(down_block)
|
296
1497
|
|
297
1498
|
# mid
|
1499
|
+
if transformer_layers_per_mid_block is None:
|
1500
|
+
transformer_layers_per_mid_block = (
|
1501
|
+
transformer_layers_per_block[-1] if isinstance(transformer_layers_per_block[-1], int) else 1
|
1502
|
+
)
|
1503
|
+
|
298
1504
|
if use_motion_mid_block:
|
299
1505
|
self.mid_block = UNetMidBlockCrossAttnMotion(
|
300
1506
|
in_channels=block_out_channels[-1],
|
@@ -302,13 +1508,16 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
302
1508
|
resnet_eps=norm_eps,
|
303
1509
|
resnet_act_fn=act_fn,
|
304
1510
|
output_scale_factor=mid_block_scale_factor,
|
305
|
-
cross_attention_dim=cross_attention_dim,
|
1511
|
+
cross_attention_dim=cross_attention_dim[-1],
|
306
1512
|
num_attention_heads=num_attention_heads[-1],
|
307
1513
|
resnet_groups=norm_num_groups,
|
308
1514
|
dual_cross_attention=False,
|
309
1515
|
use_linear_projection=use_linear_projection,
|
310
|
-
|
1516
|
+
num_layers=mid_block_layers,
|
1517
|
+
temporal_num_attention_heads=motion_num_attention_heads[-1],
|
311
1518
|
temporal_max_seq_length=motion_max_seq_length,
|
1519
|
+
transformer_layers_per_block=transformer_layers_per_mid_block,
|
1520
|
+
temporal_transformer_layers_per_block=temporal_transformer_layers_per_mid_block,
|
312
1521
|
)
|
313
1522
|
|
314
1523
|
else:
|
@@ -318,11 +1527,13 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
318
1527
|
resnet_eps=norm_eps,
|
319
1528
|
resnet_act_fn=act_fn,
|
320
1529
|
output_scale_factor=mid_block_scale_factor,
|
321
|
-
cross_attention_dim=cross_attention_dim,
|
1530
|
+
cross_attention_dim=cross_attention_dim[-1],
|
322
1531
|
num_attention_heads=num_attention_heads[-1],
|
323
1532
|
resnet_groups=norm_num_groups,
|
324
1533
|
dual_cross_attention=False,
|
325
1534
|
use_linear_projection=use_linear_projection,
|
1535
|
+
num_layers=mid_block_layers,
|
1536
|
+
transformer_layers_per_block=transformer_layers_per_mid_block,
|
326
1537
|
)
|
327
1538
|
|
328
1539
|
# count how many layers upsample the images
|
@@ -331,6 +1542,15 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
331
1542
|
# up
|
332
1543
|
reversed_block_out_channels = list(reversed(block_out_channels))
|
333
1544
|
reversed_num_attention_heads = list(reversed(num_attention_heads))
|
1545
|
+
reversed_layers_per_block = list(reversed(layers_per_block))
|
1546
|
+
reversed_cross_attention_dim = list(reversed(cross_attention_dim))
|
1547
|
+
reversed_motion_num_attention_heads = list(reversed(motion_num_attention_heads))
|
1548
|
+
|
1549
|
+
if reverse_transformer_layers_per_block is None:
|
1550
|
+
reverse_transformer_layers_per_block = list(reversed(transformer_layers_per_block))
|
1551
|
+
|
1552
|
+
if reverse_temporal_transformer_layers_per_block is None:
|
1553
|
+
reverse_temporal_transformer_layers_per_block = list(reversed(temporal_transformer_layers_per_block))
|
334
1554
|
|
335
1555
|
output_channel = reversed_block_out_channels[0]
|
336
1556
|
for i, up_block_type in enumerate(up_block_types):
|
@@ -347,25 +1567,47 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
347
1567
|
else:
|
348
1568
|
add_upsample = False
|
349
1569
|
|
350
|
-
|
351
|
-
|
352
|
-
|
353
|
-
|
354
|
-
|
355
|
-
|
356
|
-
|
357
|
-
|
358
|
-
|
359
|
-
|
360
|
-
|
361
|
-
|
362
|
-
|
363
|
-
|
364
|
-
|
365
|
-
|
366
|
-
|
367
|
-
|
368
|
-
|
1570
|
+
if up_block_type == "CrossAttnUpBlockMotion":
|
1571
|
+
up_block = CrossAttnUpBlockMotion(
|
1572
|
+
in_channels=input_channel,
|
1573
|
+
out_channels=output_channel,
|
1574
|
+
prev_output_channel=prev_output_channel,
|
1575
|
+
temb_channels=time_embed_dim,
|
1576
|
+
resolution_idx=i,
|
1577
|
+
num_layers=reversed_layers_per_block[i] + 1,
|
1578
|
+
transformer_layers_per_block=reverse_transformer_layers_per_block[i],
|
1579
|
+
resnet_eps=norm_eps,
|
1580
|
+
resnet_act_fn=act_fn,
|
1581
|
+
resnet_groups=norm_num_groups,
|
1582
|
+
num_attention_heads=reversed_num_attention_heads[i],
|
1583
|
+
cross_attention_dim=reversed_cross_attention_dim[i],
|
1584
|
+
add_upsample=add_upsample,
|
1585
|
+
use_linear_projection=use_linear_projection,
|
1586
|
+
temporal_num_attention_heads=reversed_motion_num_attention_heads[i],
|
1587
|
+
temporal_max_seq_length=motion_max_seq_length,
|
1588
|
+
temporal_transformer_layers_per_block=reverse_temporal_transformer_layers_per_block[i],
|
1589
|
+
)
|
1590
|
+
elif up_block_type == "UpBlockMotion":
|
1591
|
+
up_block = UpBlockMotion(
|
1592
|
+
in_channels=input_channel,
|
1593
|
+
prev_output_channel=prev_output_channel,
|
1594
|
+
out_channels=output_channel,
|
1595
|
+
temb_channels=time_embed_dim,
|
1596
|
+
resolution_idx=i,
|
1597
|
+
num_layers=reversed_layers_per_block[i] + 1,
|
1598
|
+
resnet_eps=norm_eps,
|
1599
|
+
resnet_act_fn=act_fn,
|
1600
|
+
resnet_groups=norm_num_groups,
|
1601
|
+
add_upsample=add_upsample,
|
1602
|
+
temporal_num_attention_heads=reversed_motion_num_attention_heads[i],
|
1603
|
+
temporal_max_seq_length=motion_max_seq_length,
|
1604
|
+
temporal_transformer_layers_per_block=reverse_temporal_transformer_layers_per_block[i],
|
1605
|
+
)
|
1606
|
+
else:
|
1607
|
+
raise ValueError(
|
1608
|
+
"Invalid `up_block_type` encountered. Must be one of `CrossAttnUpBlockMotion` or `UpBlockMotion`"
|
1609
|
+
)
|
1610
|
+
|
369
1611
|
self.up_blocks.append(up_block)
|
370
1612
|
prev_output_channel = output_channel
|
371
1613
|
|
@@ -393,8 +1635,29 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
393
1635
|
):
|
394
1636
|
has_motion_adapter = motion_adapter is not None
|
395
1637
|
|
1638
|
+
if has_motion_adapter:
|
1639
|
+
motion_adapter.to(device=unet.device)
|
1640
|
+
|
1641
|
+
# check compatibility of number of blocks
|
1642
|
+
if len(unet.config["down_block_types"]) != len(motion_adapter.config["block_out_channels"]):
|
1643
|
+
raise ValueError("Incompatible Motion Adapter, got different number of blocks")
|
1644
|
+
|
1645
|
+
# check layers compatibility for each block
|
1646
|
+
if isinstance(unet.config["layers_per_block"], int):
|
1647
|
+
expanded_layers_per_block = [unet.config["layers_per_block"]] * len(unet.config["down_block_types"])
|
1648
|
+
else:
|
1649
|
+
expanded_layers_per_block = list(unet.config["layers_per_block"])
|
1650
|
+
if isinstance(motion_adapter.config["motion_layers_per_block"], int):
|
1651
|
+
expanded_adapter_layers_per_block = [motion_adapter.config["motion_layers_per_block"]] * len(
|
1652
|
+
motion_adapter.config["block_out_channels"]
|
1653
|
+
)
|
1654
|
+
else:
|
1655
|
+
expanded_adapter_layers_per_block = list(motion_adapter.config["motion_layers_per_block"])
|
1656
|
+
if expanded_layers_per_block != expanded_adapter_layers_per_block:
|
1657
|
+
raise ValueError("Incompatible Motion Adapter, got different number of layers per block")
|
1658
|
+
|
396
1659
|
# based on https://github.com/guoyww/AnimateDiff/blob/895f3220c06318ea0760131ec70408b466c49333/animatediff/models/unet.py#L459
|
397
|
-
config = unet.config
|
1660
|
+
config = dict(unet.config)
|
398
1661
|
config["_class_name"] = cls.__name__
|
399
1662
|
|
400
1663
|
down_blocks = []
|
@@ -411,13 +1674,20 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
411
1674
|
up_blocks.append("CrossAttnUpBlockMotion")
|
412
1675
|
else:
|
413
1676
|
up_blocks.append("UpBlockMotion")
|
414
|
-
|
415
1677
|
config["up_block_types"] = up_blocks
|
416
1678
|
|
417
1679
|
if has_motion_adapter:
|
418
1680
|
config["motion_num_attention_heads"] = motion_adapter.config["motion_num_attention_heads"]
|
419
1681
|
config["motion_max_seq_length"] = motion_adapter.config["motion_max_seq_length"]
|
420
1682
|
config["use_motion_mid_block"] = motion_adapter.config["use_motion_mid_block"]
|
1683
|
+
config["layers_per_block"] = motion_adapter.config["motion_layers_per_block"]
|
1684
|
+
config["temporal_transformer_layers_per_mid_block"] = motion_adapter.config[
|
1685
|
+
"motion_transformer_layers_per_mid_block"
|
1686
|
+
]
|
1687
|
+
config["temporal_transformer_layers_per_block"] = motion_adapter.config[
|
1688
|
+
"motion_transformer_layers_per_block"
|
1689
|
+
]
|
1690
|
+
config["motion_num_attention_heads"] = motion_adapter.config["motion_num_attention_heads"]
|
421
1691
|
|
422
1692
|
# For PIA UNets we need to set the number input channels to 9
|
423
1693
|
if motion_adapter.config["conv_in_channels"]:
|
@@ -427,6 +1697,9 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
427
1697
|
if not config.get("num_attention_heads"):
|
428
1698
|
config["num_attention_heads"] = config["attention_head_dim"]
|
429
1699
|
|
1700
|
+
expected_kwargs, optional_kwargs = cls._get_signature_keys(cls)
|
1701
|
+
config = FrozenDict({k: config.get(k) for k in config if k in expected_kwargs or k in optional_kwargs})
|
1702
|
+
config["_class_name"] = cls.__name__
|
430
1703
|
model = cls.from_config(config)
|
431
1704
|
|
432
1705
|
if not load_weights:
|
@@ -446,6 +1719,36 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
446
1719
|
model.time_proj.load_state_dict(unet.time_proj.state_dict())
|
447
1720
|
model.time_embedding.load_state_dict(unet.time_embedding.state_dict())
|
448
1721
|
|
1722
|
+
if any(
|
1723
|
+
isinstance(proc, (IPAdapterAttnProcessor, IPAdapterAttnProcessor2_0))
|
1724
|
+
for proc in unet.attn_processors.values()
|
1725
|
+
):
|
1726
|
+
attn_procs = {}
|
1727
|
+
for name, processor in unet.attn_processors.items():
|
1728
|
+
if name.endswith("attn1.processor"):
|
1729
|
+
attn_processor_class = (
|
1730
|
+
AttnProcessor2_0 if hasattr(F, "scaled_dot_product_attention") else AttnProcessor
|
1731
|
+
)
|
1732
|
+
attn_procs[name] = attn_processor_class()
|
1733
|
+
else:
|
1734
|
+
attn_processor_class = (
|
1735
|
+
IPAdapterAttnProcessor2_0
|
1736
|
+
if hasattr(F, "scaled_dot_product_attention")
|
1737
|
+
else IPAdapterAttnProcessor
|
1738
|
+
)
|
1739
|
+
attn_procs[name] = attn_processor_class(
|
1740
|
+
hidden_size=processor.hidden_size,
|
1741
|
+
cross_attention_dim=processor.cross_attention_dim,
|
1742
|
+
scale=processor.scale,
|
1743
|
+
num_tokens=processor.num_tokens,
|
1744
|
+
)
|
1745
|
+
for name, processor in model.attn_processors.items():
|
1746
|
+
if name not in attn_procs:
|
1747
|
+
attn_procs[name] = processor.__class__()
|
1748
|
+
model.set_attn_processor(attn_procs)
|
1749
|
+
model.config.encoder_hid_dim_type = "ip_image_proj"
|
1750
|
+
model.encoder_hid_proj = unet.encoder_hid_proj
|
1751
|
+
|
449
1752
|
for i, down_block in enumerate(unet.down_blocks):
|
450
1753
|
model.down_blocks[i].resnets.load_state_dict(down_block.resnets.state_dict())
|
451
1754
|
if hasattr(model.down_blocks[i], "attentions"):
|
@@ -559,7 +1862,7 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
559
1862
|
|
560
1863
|
def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
|
561
1864
|
if hasattr(module, "get_processor"):
|
562
|
-
processors[f"{name}.processor"] = module.get_processor(
|
1865
|
+
processors[f"{name}.processor"] = module.get_processor()
|
563
1866
|
|
564
1867
|
for sub_name, child in module.named_children():
|
565
1868
|
fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
|
@@ -606,7 +1909,6 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
606
1909
|
for name, module in self.named_children():
|
607
1910
|
fn_recursive_attn_processor(name, module, processor)
|
608
1911
|
|
609
|
-
# Copied from diffusers.models.unets.unet_3d_condition.UNet3DConditionModel.enable_forward_chunking
|
610
1912
|
def enable_forward_chunking(self, chunk_size: Optional[int] = None, dim: int = 0) -> None:
|
611
1913
|
"""
|
612
1914
|
Sets the attention processor to use [feed forward
|
@@ -636,7 +1938,6 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
636
1938
|
for module in self.children():
|
637
1939
|
fn_recursive_feed_forward(module, chunk_size, dim)
|
638
1940
|
|
639
|
-
# Copied from diffusers.models.unets.unet_3d_condition.UNet3DConditionModel.disable_forward_chunking
|
640
1941
|
def disable_forward_chunking(self) -> None:
|
641
1942
|
def fn_recursive_feed_forward(module: torch.nn.Module, chunk_size: int, dim: int):
|
642
1943
|
if hasattr(module, "set_chunk_feed_forward"):
|
@@ -705,8 +2006,8 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
705
2006
|
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections
|
706
2007
|
def fuse_qkv_projections(self):
|
707
2008
|
"""
|
708
|
-
Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query,
|
709
|
-
|
2009
|
+
Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
|
2010
|
+
are fused. For cross-attention modules, key and value projection matrices are fused.
|
710
2011
|
|
711
2012
|
<Tip warning={true}>
|
712
2013
|
|
@@ -726,6 +2027,8 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
726
2027
|
if isinstance(module, Attention):
|
727
2028
|
module.fuse_projections(fuse=True)
|
728
2029
|
|
2030
|
+
self.set_attn_processor(FusedAttnProcessor2_0())
|
2031
|
+
|
729
2032
|
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
|
730
2033
|
def unfuse_qkv_projections(self):
|
731
2034
|
"""Disables the fused QKV projection if enabled.
|
@@ -742,7 +2045,7 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
742
2045
|
|
743
2046
|
def forward(
|
744
2047
|
self,
|
745
|
-
sample: torch.
|
2048
|
+
sample: torch.Tensor,
|
746
2049
|
timestep: Union[torch.Tensor, float, int],
|
747
2050
|
encoder_hidden_states: torch.Tensor,
|
748
2051
|
timestep_cond: Optional[torch.Tensor] = None,
|
@@ -752,15 +2055,15 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
752
2055
|
down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
|
753
2056
|
mid_block_additional_residual: Optional[torch.Tensor] = None,
|
754
2057
|
return_dict: bool = True,
|
755
|
-
) -> Union[
|
2058
|
+
) -> Union[UNetMotionOutput, Tuple[torch.Tensor]]:
|
756
2059
|
r"""
|
757
2060
|
The [`UNetMotionModel`] forward method.
|
758
2061
|
|
759
2062
|
Args:
|
760
|
-
sample (`torch.
|
2063
|
+
sample (`torch.Tensor`):
|
761
2064
|
The noisy input tensor with the following shape `(batch, num_frames, channel, height, width`.
|
762
|
-
timestep (`torch.
|
763
|
-
encoder_hidden_states (`torch.
|
2065
|
+
timestep (`torch.Tensor` or `float` or `int`): The number of timesteps to denoise an input.
|
2066
|
+
encoder_hidden_states (`torch.Tensor`):
|
764
2067
|
The encoder hidden states with shape `(batch, sequence_length, feature_dim)`.
|
765
2068
|
timestep_cond: (`torch.Tensor`, *optional*, defaults to `None`):
|
766
2069
|
Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed
|
@@ -778,13 +2081,13 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
778
2081
|
mid_block_additional_residual: (`torch.Tensor`, *optional*):
|
779
2082
|
A tensor that if specified is added to the residual of the middle unet block.
|
780
2083
|
return_dict (`bool`, *optional*, defaults to `True`):
|
781
|
-
Whether or not to return a [`~models.
|
2084
|
+
Whether or not to return a [`~models.unets.unet_motion_model.UNetMotionOutput`] instead of a plain
|
782
2085
|
tuple.
|
783
2086
|
|
784
2087
|
Returns:
|
785
|
-
[`~models.
|
786
|
-
If `return_dict` is True, an [`~models.
|
787
|
-
a `tuple` is returned where the first element is the sample tensor.
|
2088
|
+
[`~models.unets.unet_motion_model.UNetMotionOutput`] or `tuple`:
|
2089
|
+
If `return_dict` is True, an [`~models.unets.unet_motion_model.UNetMotionOutput`] is returned,
|
2090
|
+
otherwise a `tuple` is returned where the first element is the sample tensor.
|
788
2091
|
"""
|
789
2092
|
# By default samples have to be AT least a multiple of the overall upsampling factor.
|
790
2093
|
# The overall upsampling factor is equal to 2 ** (# num of upsampling layears).
|
@@ -831,8 +2134,29 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
831
2134
|
t_emb = t_emb.to(dtype=self.dtype)
|
832
2135
|
|
833
2136
|
emb = self.time_embedding(t_emb, timestep_cond)
|
2137
|
+
aug_emb = None
|
2138
|
+
|
2139
|
+
if self.config.addition_embed_type == "text_time":
|
2140
|
+
if "text_embeds" not in added_cond_kwargs:
|
2141
|
+
raise ValueError(
|
2142
|
+
f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `text_embeds` to be passed in `added_cond_kwargs`"
|
2143
|
+
)
|
2144
|
+
|
2145
|
+
text_embeds = added_cond_kwargs.get("text_embeds")
|
2146
|
+
if "time_ids" not in added_cond_kwargs:
|
2147
|
+
raise ValueError(
|
2148
|
+
f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `time_ids` to be passed in `added_cond_kwargs`"
|
2149
|
+
)
|
2150
|
+
time_ids = added_cond_kwargs.get("time_ids")
|
2151
|
+
time_embeds = self.add_time_proj(time_ids.flatten())
|
2152
|
+
time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
|
2153
|
+
|
2154
|
+
add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
|
2155
|
+
add_embeds = add_embeds.to(emb.dtype)
|
2156
|
+
aug_emb = self.add_embedding(add_embeds)
|
2157
|
+
|
2158
|
+
emb = emb if aug_emb is None else emb + aug_emb
|
834
2159
|
emb = emb.repeat_interleave(repeats=num_frames, dim=0)
|
835
|
-
encoder_hidden_states = encoder_hidden_states.repeat_interleave(repeats=num_frames, dim=0)
|
836
2160
|
|
837
2161
|
if self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "ip_image_proj":
|
838
2162
|
if "image_embeds" not in added_cond_kwargs:
|
@@ -945,4 +2269,4 @@ class UNetMotionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
|
945
2269
|
if not return_dict:
|
946
2270
|
return (sample,)
|
947
2271
|
|
948
|
-
return
|
2272
|
+
return UNetMotionOutput(sample=sample)
|