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
@@ -0,0 +1,788 @@
|
|
1
|
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
|
15
|
+
from dataclasses import dataclass
|
16
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
17
|
+
|
18
|
+
import torch
|
19
|
+
from torch import nn
|
20
|
+
from torch.nn import functional as F
|
21
|
+
|
22
|
+
from ...configuration_utils import ConfigMixin, register_to_config
|
23
|
+
from ...loaders import FromOriginalModelMixin
|
24
|
+
from ...utils import BaseOutput, logging
|
25
|
+
from ..attention_processor import (
|
26
|
+
ADDED_KV_ATTENTION_PROCESSORS,
|
27
|
+
CROSS_ATTENTION_PROCESSORS,
|
28
|
+
AttentionProcessor,
|
29
|
+
AttnAddedKVProcessor,
|
30
|
+
AttnProcessor,
|
31
|
+
)
|
32
|
+
from ..embeddings import TimestepEmbedding, Timesteps
|
33
|
+
from ..modeling_utils import ModelMixin
|
34
|
+
from ..unets.unet_2d_blocks import UNetMidBlock2DCrossAttn
|
35
|
+
from ..unets.unet_2d_condition import UNet2DConditionModel
|
36
|
+
from ..unets.unet_motion_model import CrossAttnDownBlockMotion, DownBlockMotion
|
37
|
+
|
38
|
+
|
39
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
40
|
+
|
41
|
+
|
42
|
+
@dataclass
|
43
|
+
class SparseControlNetOutput(BaseOutput):
|
44
|
+
"""
|
45
|
+
The output of [`SparseControlNetModel`].
|
46
|
+
|
47
|
+
Args:
|
48
|
+
down_block_res_samples (`tuple[torch.Tensor]`):
|
49
|
+
A tuple of downsample activations at different resolutions for each downsampling block. Each tensor should
|
50
|
+
be of shape `(batch_size, channel * resolution, height //resolution, width // resolution)`. Output can be
|
51
|
+
used to condition the original UNet's downsampling activations.
|
52
|
+
mid_down_block_re_sample (`torch.Tensor`):
|
53
|
+
The activation of the middle block (the lowest sample resolution). Each tensor should be of shape
|
54
|
+
`(batch_size, channel * lowest_resolution, height // lowest_resolution, width // lowest_resolution)`.
|
55
|
+
Output can be used to condition the original UNet's middle block activation.
|
56
|
+
"""
|
57
|
+
|
58
|
+
down_block_res_samples: Tuple[torch.Tensor]
|
59
|
+
mid_block_res_sample: torch.Tensor
|
60
|
+
|
61
|
+
|
62
|
+
class SparseControlNetConditioningEmbedding(nn.Module):
|
63
|
+
def __init__(
|
64
|
+
self,
|
65
|
+
conditioning_embedding_channels: int,
|
66
|
+
conditioning_channels: int = 3,
|
67
|
+
block_out_channels: Tuple[int, ...] = (16, 32, 96, 256),
|
68
|
+
):
|
69
|
+
super().__init__()
|
70
|
+
|
71
|
+
self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
|
72
|
+
self.blocks = nn.ModuleList([])
|
73
|
+
|
74
|
+
for i in range(len(block_out_channels) - 1):
|
75
|
+
channel_in = block_out_channels[i]
|
76
|
+
channel_out = block_out_channels[i + 1]
|
77
|
+
self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
|
78
|
+
self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2))
|
79
|
+
|
80
|
+
self.conv_out = zero_module(
|
81
|
+
nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
|
82
|
+
)
|
83
|
+
|
84
|
+
def forward(self, conditioning: torch.Tensor) -> torch.Tensor:
|
85
|
+
embedding = self.conv_in(conditioning)
|
86
|
+
embedding = F.silu(embedding)
|
87
|
+
|
88
|
+
for block in self.blocks:
|
89
|
+
embedding = block(embedding)
|
90
|
+
embedding = F.silu(embedding)
|
91
|
+
|
92
|
+
embedding = self.conv_out(embedding)
|
93
|
+
return embedding
|
94
|
+
|
95
|
+
|
96
|
+
class SparseControlNetModel(ModelMixin, ConfigMixin, FromOriginalModelMixin):
|
97
|
+
"""
|
98
|
+
A SparseControlNet model as described in [SparseCtrl: Adding Sparse Controls to Text-to-Video Diffusion
|
99
|
+
Models](https://arxiv.org/abs/2311.16933).
|
100
|
+
|
101
|
+
Args:
|
102
|
+
in_channels (`int`, defaults to 4):
|
103
|
+
The number of channels in the input sample.
|
104
|
+
conditioning_channels (`int`, defaults to 4):
|
105
|
+
The number of input channels in the controlnet conditional embedding module. If
|
106
|
+
`concat_condition_embedding` is True, the value provided here is incremented by 1.
|
107
|
+
flip_sin_to_cos (`bool`, defaults to `True`):
|
108
|
+
Whether to flip the sin to cos in the time embedding.
|
109
|
+
freq_shift (`int`, defaults to 0):
|
110
|
+
The frequency shift to apply to the time embedding.
|
111
|
+
down_block_types (`tuple[str]`, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
|
112
|
+
The tuple of downsample blocks to use.
|
113
|
+
only_cross_attention (`Union[bool, Tuple[bool]]`, defaults to `False`):
|
114
|
+
block_out_channels (`tuple[int]`, defaults to `(320, 640, 1280, 1280)`):
|
115
|
+
The tuple of output channels for each block.
|
116
|
+
layers_per_block (`int`, defaults to 2):
|
117
|
+
The number of layers per block.
|
118
|
+
downsample_padding (`int`, defaults to 1):
|
119
|
+
The padding to use for the downsampling convolution.
|
120
|
+
mid_block_scale_factor (`float`, defaults to 1):
|
121
|
+
The scale factor to use for the mid block.
|
122
|
+
act_fn (`str`, defaults to "silu"):
|
123
|
+
The activation function to use.
|
124
|
+
norm_num_groups (`int`, *optional*, defaults to 32):
|
125
|
+
The number of groups to use for the normalization. If None, normalization and activation layers is skipped
|
126
|
+
in post-processing.
|
127
|
+
norm_eps (`float`, defaults to 1e-5):
|
128
|
+
The epsilon to use for the normalization.
|
129
|
+
cross_attention_dim (`int`, defaults to 1280):
|
130
|
+
The dimension of the cross attention features.
|
131
|
+
transformer_layers_per_block (`int` or `Tuple[int]`, *optional*, defaults to 1):
|
132
|
+
The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
|
133
|
+
[`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
|
134
|
+
[`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
|
135
|
+
transformer_layers_per_mid_block (`int` or `Tuple[int]`, *optional*, defaults to 1):
|
136
|
+
The number of transformer layers to use in each layer in the middle block.
|
137
|
+
attention_head_dim (`int` or `Tuple[int]`, defaults to 8):
|
138
|
+
The dimension of the attention heads.
|
139
|
+
num_attention_heads (`int` or `Tuple[int]`, *optional*):
|
140
|
+
The number of heads to use for multi-head attention.
|
141
|
+
use_linear_projection (`bool`, defaults to `False`):
|
142
|
+
upcast_attention (`bool`, defaults to `False`):
|
143
|
+
resnet_time_scale_shift (`str`, defaults to `"default"`):
|
144
|
+
Time scale shift config for ResNet blocks (see `ResnetBlock2D`). Choose from `default` or `scale_shift`.
|
145
|
+
conditioning_embedding_out_channels (`Tuple[int]`, defaults to `(16, 32, 96, 256)`):
|
146
|
+
The tuple of output channel for each block in the `conditioning_embedding` layer.
|
147
|
+
global_pool_conditions (`bool`, defaults to `False`):
|
148
|
+
TODO(Patrick) - unused parameter
|
149
|
+
controlnet_conditioning_channel_order (`str`, defaults to `rgb`):
|
150
|
+
motion_max_seq_length (`int`, defaults to `32`):
|
151
|
+
The maximum sequence length to use in the motion module.
|
152
|
+
motion_num_attention_heads (`int` or `Tuple[int]`, defaults to `8`):
|
153
|
+
The number of heads to use in each attention layer of the motion module.
|
154
|
+
concat_conditioning_mask (`bool`, defaults to `True`):
|
155
|
+
use_simplified_condition_embedding (`bool`, defaults to `True`):
|
156
|
+
"""
|
157
|
+
|
158
|
+
_supports_gradient_checkpointing = True
|
159
|
+
|
160
|
+
@register_to_config
|
161
|
+
def __init__(
|
162
|
+
self,
|
163
|
+
in_channels: int = 4,
|
164
|
+
conditioning_channels: int = 4,
|
165
|
+
flip_sin_to_cos: bool = True,
|
166
|
+
freq_shift: int = 0,
|
167
|
+
down_block_types: Tuple[str, ...] = (
|
168
|
+
"CrossAttnDownBlockMotion",
|
169
|
+
"CrossAttnDownBlockMotion",
|
170
|
+
"CrossAttnDownBlockMotion",
|
171
|
+
"DownBlockMotion",
|
172
|
+
),
|
173
|
+
only_cross_attention: Union[bool, Tuple[bool]] = False,
|
174
|
+
block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280),
|
175
|
+
layers_per_block: int = 2,
|
176
|
+
downsample_padding: int = 1,
|
177
|
+
mid_block_scale_factor: float = 1,
|
178
|
+
act_fn: str = "silu",
|
179
|
+
norm_num_groups: Optional[int] = 32,
|
180
|
+
norm_eps: float = 1e-5,
|
181
|
+
cross_attention_dim: int = 768,
|
182
|
+
transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
|
183
|
+
transformer_layers_per_mid_block: Optional[Union[int, Tuple[int]]] = None,
|
184
|
+
temporal_transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
|
185
|
+
attention_head_dim: Union[int, Tuple[int, ...]] = 8,
|
186
|
+
num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None,
|
187
|
+
use_linear_projection: bool = False,
|
188
|
+
upcast_attention: bool = False,
|
189
|
+
resnet_time_scale_shift: str = "default",
|
190
|
+
conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
|
191
|
+
global_pool_conditions: bool = False,
|
192
|
+
controlnet_conditioning_channel_order: str = "rgb",
|
193
|
+
motion_max_seq_length: int = 32,
|
194
|
+
motion_num_attention_heads: int = 8,
|
195
|
+
concat_conditioning_mask: bool = True,
|
196
|
+
use_simplified_condition_embedding: bool = True,
|
197
|
+
):
|
198
|
+
super().__init__()
|
199
|
+
self.use_simplified_condition_embedding = use_simplified_condition_embedding
|
200
|
+
|
201
|
+
# If `num_attention_heads` is not defined (which is the case for most models)
|
202
|
+
# it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
|
203
|
+
# The reason for this behavior is to correct for incorrectly named variables that were introduced
|
204
|
+
# when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
|
205
|
+
# Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
|
206
|
+
# which is why we correct for the naming here.
|
207
|
+
num_attention_heads = num_attention_heads or attention_head_dim
|
208
|
+
|
209
|
+
# Check inputs
|
210
|
+
if len(block_out_channels) != len(down_block_types):
|
211
|
+
raise ValueError(
|
212
|
+
f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."
|
213
|
+
)
|
214
|
+
|
215
|
+
if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
|
216
|
+
raise ValueError(
|
217
|
+
f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
|
218
|
+
)
|
219
|
+
|
220
|
+
if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
|
221
|
+
raise ValueError(
|
222
|
+
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}."
|
223
|
+
)
|
224
|
+
|
225
|
+
if isinstance(transformer_layers_per_block, int):
|
226
|
+
transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
|
227
|
+
if isinstance(temporal_transformer_layers_per_block, int):
|
228
|
+
temporal_transformer_layers_per_block = [temporal_transformer_layers_per_block] * len(down_block_types)
|
229
|
+
|
230
|
+
# input
|
231
|
+
conv_in_kernel = 3
|
232
|
+
conv_in_padding = (conv_in_kernel - 1) // 2
|
233
|
+
self.conv_in = nn.Conv2d(
|
234
|
+
in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
|
235
|
+
)
|
236
|
+
|
237
|
+
if concat_conditioning_mask:
|
238
|
+
conditioning_channels = conditioning_channels + 1
|
239
|
+
|
240
|
+
self.concat_conditioning_mask = concat_conditioning_mask
|
241
|
+
|
242
|
+
# control net conditioning embedding
|
243
|
+
if use_simplified_condition_embedding:
|
244
|
+
self.controlnet_cond_embedding = zero_module(
|
245
|
+
nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
|
246
|
+
)
|
247
|
+
else:
|
248
|
+
self.controlnet_cond_embedding = SparseControlNetConditioningEmbedding(
|
249
|
+
conditioning_embedding_channels=block_out_channels[0],
|
250
|
+
block_out_channels=conditioning_embedding_out_channels,
|
251
|
+
conditioning_channels=conditioning_channels,
|
252
|
+
)
|
253
|
+
|
254
|
+
# time
|
255
|
+
time_embed_dim = block_out_channels[0] * 4
|
256
|
+
self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
|
257
|
+
timestep_input_dim = block_out_channels[0]
|
258
|
+
|
259
|
+
self.time_embedding = TimestepEmbedding(
|
260
|
+
timestep_input_dim,
|
261
|
+
time_embed_dim,
|
262
|
+
act_fn=act_fn,
|
263
|
+
)
|
264
|
+
|
265
|
+
self.down_blocks = nn.ModuleList([])
|
266
|
+
self.controlnet_down_blocks = nn.ModuleList([])
|
267
|
+
|
268
|
+
if isinstance(cross_attention_dim, int):
|
269
|
+
cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
|
270
|
+
|
271
|
+
if isinstance(only_cross_attention, bool):
|
272
|
+
only_cross_attention = [only_cross_attention] * len(down_block_types)
|
273
|
+
|
274
|
+
if isinstance(attention_head_dim, int):
|
275
|
+
attention_head_dim = (attention_head_dim,) * len(down_block_types)
|
276
|
+
|
277
|
+
if isinstance(num_attention_heads, int):
|
278
|
+
num_attention_heads = (num_attention_heads,) * len(down_block_types)
|
279
|
+
|
280
|
+
if isinstance(motion_num_attention_heads, int):
|
281
|
+
motion_num_attention_heads = (motion_num_attention_heads,) * len(down_block_types)
|
282
|
+
|
283
|
+
# down
|
284
|
+
output_channel = block_out_channels[0]
|
285
|
+
|
286
|
+
controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
|
287
|
+
controlnet_block = zero_module(controlnet_block)
|
288
|
+
self.controlnet_down_blocks.append(controlnet_block)
|
289
|
+
|
290
|
+
for i, down_block_type in enumerate(down_block_types):
|
291
|
+
input_channel = output_channel
|
292
|
+
output_channel = block_out_channels[i]
|
293
|
+
is_final_block = i == len(block_out_channels) - 1
|
294
|
+
|
295
|
+
if down_block_type == "CrossAttnDownBlockMotion":
|
296
|
+
down_block = CrossAttnDownBlockMotion(
|
297
|
+
in_channels=input_channel,
|
298
|
+
out_channels=output_channel,
|
299
|
+
temb_channels=time_embed_dim,
|
300
|
+
dropout=0,
|
301
|
+
num_layers=layers_per_block,
|
302
|
+
transformer_layers_per_block=transformer_layers_per_block[i],
|
303
|
+
resnet_eps=norm_eps,
|
304
|
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
305
|
+
resnet_act_fn=act_fn,
|
306
|
+
resnet_groups=norm_num_groups,
|
307
|
+
resnet_pre_norm=True,
|
308
|
+
num_attention_heads=num_attention_heads[i],
|
309
|
+
cross_attention_dim=cross_attention_dim[i],
|
310
|
+
add_downsample=not is_final_block,
|
311
|
+
dual_cross_attention=False,
|
312
|
+
use_linear_projection=use_linear_projection,
|
313
|
+
only_cross_attention=only_cross_attention[i],
|
314
|
+
upcast_attention=upcast_attention,
|
315
|
+
temporal_num_attention_heads=motion_num_attention_heads[i],
|
316
|
+
temporal_max_seq_length=motion_max_seq_length,
|
317
|
+
temporal_transformer_layers_per_block=temporal_transformer_layers_per_block[i],
|
318
|
+
temporal_double_self_attention=False,
|
319
|
+
)
|
320
|
+
elif down_block_type == "DownBlockMotion":
|
321
|
+
down_block = DownBlockMotion(
|
322
|
+
in_channels=input_channel,
|
323
|
+
out_channels=output_channel,
|
324
|
+
temb_channels=time_embed_dim,
|
325
|
+
dropout=0,
|
326
|
+
num_layers=layers_per_block,
|
327
|
+
resnet_eps=norm_eps,
|
328
|
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
329
|
+
resnet_act_fn=act_fn,
|
330
|
+
resnet_groups=norm_num_groups,
|
331
|
+
resnet_pre_norm=True,
|
332
|
+
add_downsample=not is_final_block,
|
333
|
+
temporal_num_attention_heads=motion_num_attention_heads[i],
|
334
|
+
temporal_max_seq_length=motion_max_seq_length,
|
335
|
+
temporal_transformer_layers_per_block=temporal_transformer_layers_per_block[i],
|
336
|
+
temporal_double_self_attention=False,
|
337
|
+
)
|
338
|
+
else:
|
339
|
+
raise ValueError(
|
340
|
+
"Invalid `block_type` encountered. Must be one of `CrossAttnDownBlockMotion` or `DownBlockMotion`"
|
341
|
+
)
|
342
|
+
|
343
|
+
self.down_blocks.append(down_block)
|
344
|
+
|
345
|
+
for _ in range(layers_per_block):
|
346
|
+
controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
|
347
|
+
controlnet_block = zero_module(controlnet_block)
|
348
|
+
self.controlnet_down_blocks.append(controlnet_block)
|
349
|
+
|
350
|
+
if not is_final_block:
|
351
|
+
controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
|
352
|
+
controlnet_block = zero_module(controlnet_block)
|
353
|
+
self.controlnet_down_blocks.append(controlnet_block)
|
354
|
+
|
355
|
+
# mid
|
356
|
+
mid_block_channels = block_out_channels[-1]
|
357
|
+
|
358
|
+
controlnet_block = nn.Conv2d(mid_block_channels, mid_block_channels, kernel_size=1)
|
359
|
+
controlnet_block = zero_module(controlnet_block)
|
360
|
+
self.controlnet_mid_block = controlnet_block
|
361
|
+
|
362
|
+
if transformer_layers_per_mid_block is None:
|
363
|
+
transformer_layers_per_mid_block = (
|
364
|
+
transformer_layers_per_block[-1] if isinstance(transformer_layers_per_block[-1], int) else 1
|
365
|
+
)
|
366
|
+
|
367
|
+
self.mid_block = UNetMidBlock2DCrossAttn(
|
368
|
+
in_channels=mid_block_channels,
|
369
|
+
temb_channels=time_embed_dim,
|
370
|
+
dropout=0,
|
371
|
+
num_layers=1,
|
372
|
+
transformer_layers_per_block=transformer_layers_per_mid_block,
|
373
|
+
resnet_eps=norm_eps,
|
374
|
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
375
|
+
resnet_act_fn=act_fn,
|
376
|
+
resnet_groups=norm_num_groups,
|
377
|
+
resnet_pre_norm=True,
|
378
|
+
num_attention_heads=num_attention_heads[-1],
|
379
|
+
output_scale_factor=mid_block_scale_factor,
|
380
|
+
cross_attention_dim=cross_attention_dim[-1],
|
381
|
+
dual_cross_attention=False,
|
382
|
+
use_linear_projection=use_linear_projection,
|
383
|
+
upcast_attention=upcast_attention,
|
384
|
+
attention_type="default",
|
385
|
+
)
|
386
|
+
|
387
|
+
@classmethod
|
388
|
+
def from_unet(
|
389
|
+
cls,
|
390
|
+
unet: UNet2DConditionModel,
|
391
|
+
controlnet_conditioning_channel_order: str = "rgb",
|
392
|
+
conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
|
393
|
+
load_weights_from_unet: bool = True,
|
394
|
+
conditioning_channels: int = 3,
|
395
|
+
) -> "SparseControlNetModel":
|
396
|
+
r"""
|
397
|
+
Instantiate a [`SparseControlNetModel`] from [`UNet2DConditionModel`].
|
398
|
+
|
399
|
+
Parameters:
|
400
|
+
unet (`UNet2DConditionModel`):
|
401
|
+
The UNet model weights to copy to the [`SparseControlNetModel`]. All configuration options are also
|
402
|
+
copied where applicable.
|
403
|
+
"""
|
404
|
+
transformer_layers_per_block = (
|
405
|
+
unet.config.transformer_layers_per_block if "transformer_layers_per_block" in unet.config else 1
|
406
|
+
)
|
407
|
+
down_block_types = unet.config.down_block_types
|
408
|
+
|
409
|
+
for i in range(len(down_block_types)):
|
410
|
+
if "CrossAttn" in down_block_types[i]:
|
411
|
+
down_block_types[i] = "CrossAttnDownBlockMotion"
|
412
|
+
elif "Down" in down_block_types[i]:
|
413
|
+
down_block_types[i] = "DownBlockMotion"
|
414
|
+
else:
|
415
|
+
raise ValueError("Invalid `block_type` encountered. Must be a cross-attention or down block")
|
416
|
+
|
417
|
+
controlnet = cls(
|
418
|
+
in_channels=unet.config.in_channels,
|
419
|
+
conditioning_channels=conditioning_channels,
|
420
|
+
flip_sin_to_cos=unet.config.flip_sin_to_cos,
|
421
|
+
freq_shift=unet.config.freq_shift,
|
422
|
+
down_block_types=unet.config.down_block_types,
|
423
|
+
only_cross_attention=unet.config.only_cross_attention,
|
424
|
+
block_out_channels=unet.config.block_out_channels,
|
425
|
+
layers_per_block=unet.config.layers_per_block,
|
426
|
+
downsample_padding=unet.config.downsample_padding,
|
427
|
+
mid_block_scale_factor=unet.config.mid_block_scale_factor,
|
428
|
+
act_fn=unet.config.act_fn,
|
429
|
+
norm_num_groups=unet.config.norm_num_groups,
|
430
|
+
norm_eps=unet.config.norm_eps,
|
431
|
+
cross_attention_dim=unet.config.cross_attention_dim,
|
432
|
+
transformer_layers_per_block=transformer_layers_per_block,
|
433
|
+
attention_head_dim=unet.config.attention_head_dim,
|
434
|
+
num_attention_heads=unet.config.num_attention_heads,
|
435
|
+
use_linear_projection=unet.config.use_linear_projection,
|
436
|
+
upcast_attention=unet.config.upcast_attention,
|
437
|
+
resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
|
438
|
+
conditioning_embedding_out_channels=conditioning_embedding_out_channels,
|
439
|
+
controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
|
440
|
+
)
|
441
|
+
|
442
|
+
if load_weights_from_unet:
|
443
|
+
controlnet.conv_in.load_state_dict(unet.conv_in.state_dict(), strict=False)
|
444
|
+
controlnet.time_proj.load_state_dict(unet.time_proj.state_dict(), strict=False)
|
445
|
+
controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict(), strict=False)
|
446
|
+
controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict(), strict=False)
|
447
|
+
controlnet.mid_block.load_state_dict(unet.mid_block.state_dict(), strict=False)
|
448
|
+
|
449
|
+
return controlnet
|
450
|
+
|
451
|
+
@property
|
452
|
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
|
453
|
+
def attn_processors(self) -> Dict[str, AttentionProcessor]:
|
454
|
+
r"""
|
455
|
+
Returns:
|
456
|
+
`dict` of attention processors: A dictionary containing all attention processors used in the model with
|
457
|
+
indexed by its weight name.
|
458
|
+
"""
|
459
|
+
# set recursively
|
460
|
+
processors = {}
|
461
|
+
|
462
|
+
def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
|
463
|
+
if hasattr(module, "get_processor"):
|
464
|
+
processors[f"{name}.processor"] = module.get_processor()
|
465
|
+
|
466
|
+
for sub_name, child in module.named_children():
|
467
|
+
fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
|
468
|
+
|
469
|
+
return processors
|
470
|
+
|
471
|
+
for name, module in self.named_children():
|
472
|
+
fn_recursive_add_processors(name, module, processors)
|
473
|
+
|
474
|
+
return processors
|
475
|
+
|
476
|
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
|
477
|
+
def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
|
478
|
+
r"""
|
479
|
+
Sets the attention processor to use to compute attention.
|
480
|
+
|
481
|
+
Parameters:
|
482
|
+
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
|
483
|
+
The instantiated processor class or a dictionary of processor classes that will be set as the processor
|
484
|
+
for **all** `Attention` layers.
|
485
|
+
|
486
|
+
If `processor` is a dict, the key needs to define the path to the corresponding cross attention
|
487
|
+
processor. This is strongly recommended when setting trainable attention processors.
|
488
|
+
|
489
|
+
"""
|
490
|
+
count = len(self.attn_processors.keys())
|
491
|
+
|
492
|
+
if isinstance(processor, dict) and len(processor) != count:
|
493
|
+
raise ValueError(
|
494
|
+
f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
|
495
|
+
f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
|
496
|
+
)
|
497
|
+
|
498
|
+
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
|
499
|
+
if hasattr(module, "set_processor"):
|
500
|
+
if not isinstance(processor, dict):
|
501
|
+
module.set_processor(processor)
|
502
|
+
else:
|
503
|
+
module.set_processor(processor.pop(f"{name}.processor"))
|
504
|
+
|
505
|
+
for sub_name, child in module.named_children():
|
506
|
+
fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
|
507
|
+
|
508
|
+
for name, module in self.named_children():
|
509
|
+
fn_recursive_attn_processor(name, module, processor)
|
510
|
+
|
511
|
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
|
512
|
+
def set_default_attn_processor(self):
|
513
|
+
"""
|
514
|
+
Disables custom attention processors and sets the default attention implementation.
|
515
|
+
"""
|
516
|
+
if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
|
517
|
+
processor = AttnAddedKVProcessor()
|
518
|
+
elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
|
519
|
+
processor = AttnProcessor()
|
520
|
+
else:
|
521
|
+
raise ValueError(
|
522
|
+
f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
|
523
|
+
)
|
524
|
+
|
525
|
+
self.set_attn_processor(processor)
|
526
|
+
|
527
|
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attention_slice
|
528
|
+
def set_attention_slice(self, slice_size: Union[str, int, List[int]]) -> None:
|
529
|
+
r"""
|
530
|
+
Enable sliced attention computation.
|
531
|
+
|
532
|
+
When this option is enabled, the attention module splits the input tensor in slices to compute attention in
|
533
|
+
several steps. This is useful for saving some memory in exchange for a small decrease in speed.
|
534
|
+
|
535
|
+
Args:
|
536
|
+
slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
|
537
|
+
When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
|
538
|
+
`"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
|
539
|
+
provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
|
540
|
+
must be a multiple of `slice_size`.
|
541
|
+
"""
|
542
|
+
sliceable_head_dims = []
|
543
|
+
|
544
|
+
def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
|
545
|
+
if hasattr(module, "set_attention_slice"):
|
546
|
+
sliceable_head_dims.append(module.sliceable_head_dim)
|
547
|
+
|
548
|
+
for child in module.children():
|
549
|
+
fn_recursive_retrieve_sliceable_dims(child)
|
550
|
+
|
551
|
+
# retrieve number of attention layers
|
552
|
+
for module in self.children():
|
553
|
+
fn_recursive_retrieve_sliceable_dims(module)
|
554
|
+
|
555
|
+
num_sliceable_layers = len(sliceable_head_dims)
|
556
|
+
|
557
|
+
if slice_size == "auto":
|
558
|
+
# half the attention head size is usually a good trade-off between
|
559
|
+
# speed and memory
|
560
|
+
slice_size = [dim // 2 for dim in sliceable_head_dims]
|
561
|
+
elif slice_size == "max":
|
562
|
+
# make smallest slice possible
|
563
|
+
slice_size = num_sliceable_layers * [1]
|
564
|
+
|
565
|
+
slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
|
566
|
+
|
567
|
+
if len(slice_size) != len(sliceable_head_dims):
|
568
|
+
raise ValueError(
|
569
|
+
f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
|
570
|
+
f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
|
571
|
+
)
|
572
|
+
|
573
|
+
for i in range(len(slice_size)):
|
574
|
+
size = slice_size[i]
|
575
|
+
dim = sliceable_head_dims[i]
|
576
|
+
if size is not None and size > dim:
|
577
|
+
raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
|
578
|
+
|
579
|
+
# Recursively walk through all the children.
|
580
|
+
# Any children which exposes the set_attention_slice method
|
581
|
+
# gets the message
|
582
|
+
def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
|
583
|
+
if hasattr(module, "set_attention_slice"):
|
584
|
+
module.set_attention_slice(slice_size.pop())
|
585
|
+
|
586
|
+
for child in module.children():
|
587
|
+
fn_recursive_set_attention_slice(child, slice_size)
|
588
|
+
|
589
|
+
reversed_slice_size = list(reversed(slice_size))
|
590
|
+
for module in self.children():
|
591
|
+
fn_recursive_set_attention_slice(module, reversed_slice_size)
|
592
|
+
|
593
|
+
def _set_gradient_checkpointing(self, module, value: bool = False) -> None:
|
594
|
+
if isinstance(module, (CrossAttnDownBlockMotion, DownBlockMotion, UNetMidBlock2DCrossAttn)):
|
595
|
+
module.gradient_checkpointing = value
|
596
|
+
|
597
|
+
def forward(
|
598
|
+
self,
|
599
|
+
sample: torch.Tensor,
|
600
|
+
timestep: Union[torch.Tensor, float, int],
|
601
|
+
encoder_hidden_states: torch.Tensor,
|
602
|
+
controlnet_cond: torch.Tensor,
|
603
|
+
conditioning_scale: float = 1.0,
|
604
|
+
timestep_cond: Optional[torch.Tensor] = None,
|
605
|
+
attention_mask: Optional[torch.Tensor] = None,
|
606
|
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
607
|
+
conditioning_mask: Optional[torch.Tensor] = None,
|
608
|
+
guess_mode: bool = False,
|
609
|
+
return_dict: bool = True,
|
610
|
+
) -> Union[SparseControlNetOutput, Tuple[Tuple[torch.Tensor, ...], torch.Tensor]]:
|
611
|
+
"""
|
612
|
+
The [`SparseControlNetModel`] forward method.
|
613
|
+
|
614
|
+
Args:
|
615
|
+
sample (`torch.Tensor`):
|
616
|
+
The noisy input tensor.
|
617
|
+
timestep (`Union[torch.Tensor, float, int]`):
|
618
|
+
The number of timesteps to denoise an input.
|
619
|
+
encoder_hidden_states (`torch.Tensor`):
|
620
|
+
The encoder hidden states.
|
621
|
+
controlnet_cond (`torch.Tensor`):
|
622
|
+
The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
|
623
|
+
conditioning_scale (`float`, defaults to `1.0`):
|
624
|
+
The scale factor for ControlNet outputs.
|
625
|
+
class_labels (`torch.Tensor`, *optional*, defaults to `None`):
|
626
|
+
Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
|
627
|
+
timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
|
628
|
+
Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
|
629
|
+
timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
|
630
|
+
embeddings.
|
631
|
+
attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
|
632
|
+
An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
|
633
|
+
is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
|
634
|
+
negative values to the attention scores corresponding to "discard" tokens.
|
635
|
+
added_cond_kwargs (`dict`):
|
636
|
+
Additional conditions for the Stable Diffusion XL UNet.
|
637
|
+
cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
|
638
|
+
A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
|
639
|
+
guess_mode (`bool`, defaults to `False`):
|
640
|
+
In this mode, the ControlNet encoder tries its best to recognize the input content of the input even if
|
641
|
+
you remove all prompts. A `guidance_scale` between 3.0 and 5.0 is recommended.
|
642
|
+
return_dict (`bool`, defaults to `True`):
|
643
|
+
Whether or not to return a [`~models.controlnet.ControlNetOutput`] instead of a plain tuple.
|
644
|
+
Returns:
|
645
|
+
[`~models.controlnet.ControlNetOutput`] **or** `tuple`:
|
646
|
+
If `return_dict` is `True`, a [`~models.controlnet.ControlNetOutput`] is returned, otherwise a tuple is
|
647
|
+
returned where the first element is the sample tensor.
|
648
|
+
"""
|
649
|
+
sample_batch_size, sample_channels, sample_num_frames, sample_height, sample_width = sample.shape
|
650
|
+
sample = torch.zeros_like(sample)
|
651
|
+
|
652
|
+
# check channel order
|
653
|
+
channel_order = self.config.controlnet_conditioning_channel_order
|
654
|
+
|
655
|
+
if channel_order == "rgb":
|
656
|
+
# in rgb order by default
|
657
|
+
...
|
658
|
+
elif channel_order == "bgr":
|
659
|
+
controlnet_cond = torch.flip(controlnet_cond, dims=[1])
|
660
|
+
else:
|
661
|
+
raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}")
|
662
|
+
|
663
|
+
# prepare attention_mask
|
664
|
+
if attention_mask is not None:
|
665
|
+
attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
|
666
|
+
attention_mask = attention_mask.unsqueeze(1)
|
667
|
+
|
668
|
+
# 1. time
|
669
|
+
timesteps = timestep
|
670
|
+
if not torch.is_tensor(timesteps):
|
671
|
+
# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
|
672
|
+
# This would be a good case for the `match` statement (Python 3.10+)
|
673
|
+
is_mps = sample.device.type == "mps"
|
674
|
+
if isinstance(timestep, float):
|
675
|
+
dtype = torch.float32 if is_mps else torch.float64
|
676
|
+
else:
|
677
|
+
dtype = torch.int32 if is_mps else torch.int64
|
678
|
+
timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
|
679
|
+
elif len(timesteps.shape) == 0:
|
680
|
+
timesteps = timesteps[None].to(sample.device)
|
681
|
+
|
682
|
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
683
|
+
timesteps = timesteps.expand(sample.shape[0])
|
684
|
+
|
685
|
+
t_emb = self.time_proj(timesteps)
|
686
|
+
|
687
|
+
# timesteps does not contain any weights and will always return f32 tensors
|
688
|
+
# but time_embedding might actually be running in fp16. so we need to cast here.
|
689
|
+
# there might be better ways to encapsulate this.
|
690
|
+
t_emb = t_emb.to(dtype=sample.dtype)
|
691
|
+
|
692
|
+
emb = self.time_embedding(t_emb, timestep_cond)
|
693
|
+
emb = emb.repeat_interleave(sample_num_frames, dim=0)
|
694
|
+
|
695
|
+
# 2. pre-process
|
696
|
+
batch_size, channels, num_frames, height, width = sample.shape
|
697
|
+
|
698
|
+
sample = sample.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, channels, height, width)
|
699
|
+
sample = self.conv_in(sample)
|
700
|
+
|
701
|
+
batch_frames, channels, height, width = sample.shape
|
702
|
+
sample = sample[:, None].reshape(sample_batch_size, sample_num_frames, channels, height, width)
|
703
|
+
|
704
|
+
if self.concat_conditioning_mask:
|
705
|
+
controlnet_cond = torch.cat([controlnet_cond, conditioning_mask], dim=1)
|
706
|
+
|
707
|
+
batch_size, channels, num_frames, height, width = controlnet_cond.shape
|
708
|
+
controlnet_cond = controlnet_cond.permute(0, 2, 1, 3, 4).reshape(
|
709
|
+
batch_size * num_frames, channels, height, width
|
710
|
+
)
|
711
|
+
controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
|
712
|
+
batch_frames, channels, height, width = controlnet_cond.shape
|
713
|
+
controlnet_cond = controlnet_cond[:, None].reshape(batch_size, num_frames, channels, height, width)
|
714
|
+
|
715
|
+
sample = sample + controlnet_cond
|
716
|
+
|
717
|
+
batch_size, num_frames, channels, height, width = sample.shape
|
718
|
+
sample = sample.reshape(sample_batch_size * sample_num_frames, channels, height, width)
|
719
|
+
|
720
|
+
# 3. down
|
721
|
+
down_block_res_samples = (sample,)
|
722
|
+
for downsample_block in self.down_blocks:
|
723
|
+
if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
|
724
|
+
sample, res_samples = downsample_block(
|
725
|
+
hidden_states=sample,
|
726
|
+
temb=emb,
|
727
|
+
encoder_hidden_states=encoder_hidden_states,
|
728
|
+
attention_mask=attention_mask,
|
729
|
+
num_frames=num_frames,
|
730
|
+
cross_attention_kwargs=cross_attention_kwargs,
|
731
|
+
)
|
732
|
+
else:
|
733
|
+
sample, res_samples = downsample_block(hidden_states=sample, temb=emb, num_frames=num_frames)
|
734
|
+
|
735
|
+
down_block_res_samples += res_samples
|
736
|
+
|
737
|
+
# 4. mid
|
738
|
+
if self.mid_block is not None:
|
739
|
+
if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
|
740
|
+
sample = self.mid_block(
|
741
|
+
sample,
|
742
|
+
emb,
|
743
|
+
encoder_hidden_states=encoder_hidden_states,
|
744
|
+
attention_mask=attention_mask,
|
745
|
+
cross_attention_kwargs=cross_attention_kwargs,
|
746
|
+
)
|
747
|
+
else:
|
748
|
+
sample = self.mid_block(sample, emb)
|
749
|
+
|
750
|
+
# 5. Control net blocks
|
751
|
+
controlnet_down_block_res_samples = ()
|
752
|
+
|
753
|
+
for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
|
754
|
+
down_block_res_sample = controlnet_block(down_block_res_sample)
|
755
|
+
controlnet_down_block_res_samples = controlnet_down_block_res_samples + (down_block_res_sample,)
|
756
|
+
|
757
|
+
down_block_res_samples = controlnet_down_block_res_samples
|
758
|
+
mid_block_res_sample = self.controlnet_mid_block(sample)
|
759
|
+
|
760
|
+
# 6. scaling
|
761
|
+
if guess_mode and not self.config.global_pool_conditions:
|
762
|
+
scales = torch.logspace(-1, 0, len(down_block_res_samples) + 1, device=sample.device) # 0.1 to 1.0
|
763
|
+
scales = scales * conditioning_scale
|
764
|
+
down_block_res_samples = [sample * scale for sample, scale in zip(down_block_res_samples, scales)]
|
765
|
+
mid_block_res_sample = mid_block_res_sample * scales[-1] # last one
|
766
|
+
else:
|
767
|
+
down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
|
768
|
+
mid_block_res_sample = mid_block_res_sample * conditioning_scale
|
769
|
+
|
770
|
+
if self.config.global_pool_conditions:
|
771
|
+
down_block_res_samples = [
|
772
|
+
torch.mean(sample, dim=(2, 3), keepdim=True) for sample in down_block_res_samples
|
773
|
+
]
|
774
|
+
mid_block_res_sample = torch.mean(mid_block_res_sample, dim=(2, 3), keepdim=True)
|
775
|
+
|
776
|
+
if not return_dict:
|
777
|
+
return (down_block_res_samples, mid_block_res_sample)
|
778
|
+
|
779
|
+
return SparseControlNetOutput(
|
780
|
+
down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
|
781
|
+
)
|
782
|
+
|
783
|
+
|
784
|
+
# Copied from diffusers.models.controlnets.controlnet.zero_module
|
785
|
+
def zero_module(module: nn.Module) -> nn.Module:
|
786
|
+
for p in module.parameters():
|
787
|
+
nn.init.zeros_(p)
|
788
|
+
return module
|