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,1946 @@
|
|
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
|
+
from dataclasses import dataclass
|
15
|
+
from math import gcd
|
16
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
17
|
+
|
18
|
+
import torch
|
19
|
+
import torch.utils.checkpoint
|
20
|
+
from torch import Tensor, nn
|
21
|
+
|
22
|
+
from ...configuration_utils import ConfigMixin, register_to_config
|
23
|
+
from ...utils import BaseOutput, is_torch_version, logging
|
24
|
+
from ...utils.torch_utils import apply_freeu
|
25
|
+
from ..attention_processor import (
|
26
|
+
ADDED_KV_ATTENTION_PROCESSORS,
|
27
|
+
CROSS_ATTENTION_PROCESSORS,
|
28
|
+
Attention,
|
29
|
+
AttentionProcessor,
|
30
|
+
AttnAddedKVProcessor,
|
31
|
+
AttnProcessor,
|
32
|
+
FusedAttnProcessor2_0,
|
33
|
+
)
|
34
|
+
from ..embeddings import TimestepEmbedding, Timesteps
|
35
|
+
from ..modeling_utils import ModelMixin
|
36
|
+
from ..unets.unet_2d_blocks import (
|
37
|
+
CrossAttnDownBlock2D,
|
38
|
+
CrossAttnUpBlock2D,
|
39
|
+
Downsample2D,
|
40
|
+
ResnetBlock2D,
|
41
|
+
Transformer2DModel,
|
42
|
+
UNetMidBlock2DCrossAttn,
|
43
|
+
Upsample2D,
|
44
|
+
)
|
45
|
+
from ..unets.unet_2d_condition import UNet2DConditionModel
|
46
|
+
from .controlnet import ControlNetConditioningEmbedding
|
47
|
+
|
48
|
+
|
49
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
50
|
+
|
51
|
+
|
52
|
+
@dataclass
|
53
|
+
class ControlNetXSOutput(BaseOutput):
|
54
|
+
"""
|
55
|
+
The output of [`UNetControlNetXSModel`].
|
56
|
+
|
57
|
+
Args:
|
58
|
+
sample (`Tensor` of shape `(batch_size, num_channels, height, width)`):
|
59
|
+
The output of the `UNetControlNetXSModel`. Unlike `ControlNetOutput` this is NOT to be added to the base
|
60
|
+
model output, but is already the final output.
|
61
|
+
"""
|
62
|
+
|
63
|
+
sample: Tensor = None
|
64
|
+
|
65
|
+
|
66
|
+
class DownBlockControlNetXSAdapter(nn.Module):
|
67
|
+
"""Components that together with corresponding components from the base model will form a
|
68
|
+
`ControlNetXSCrossAttnDownBlock2D`"""
|
69
|
+
|
70
|
+
def __init__(
|
71
|
+
self,
|
72
|
+
resnets: nn.ModuleList,
|
73
|
+
base_to_ctrl: nn.ModuleList,
|
74
|
+
ctrl_to_base: nn.ModuleList,
|
75
|
+
attentions: Optional[nn.ModuleList] = None,
|
76
|
+
downsampler: Optional[nn.Conv2d] = None,
|
77
|
+
):
|
78
|
+
super().__init__()
|
79
|
+
self.resnets = resnets
|
80
|
+
self.base_to_ctrl = base_to_ctrl
|
81
|
+
self.ctrl_to_base = ctrl_to_base
|
82
|
+
self.attentions = attentions
|
83
|
+
self.downsamplers = downsampler
|
84
|
+
|
85
|
+
|
86
|
+
class MidBlockControlNetXSAdapter(nn.Module):
|
87
|
+
"""Components that together with corresponding components from the base model will form a
|
88
|
+
`ControlNetXSCrossAttnMidBlock2D`"""
|
89
|
+
|
90
|
+
def __init__(self, midblock: UNetMidBlock2DCrossAttn, base_to_ctrl: nn.ModuleList, ctrl_to_base: nn.ModuleList):
|
91
|
+
super().__init__()
|
92
|
+
self.midblock = midblock
|
93
|
+
self.base_to_ctrl = base_to_ctrl
|
94
|
+
self.ctrl_to_base = ctrl_to_base
|
95
|
+
|
96
|
+
|
97
|
+
class UpBlockControlNetXSAdapter(nn.Module):
|
98
|
+
"""Components that together with corresponding components from the base model will form a `ControlNetXSCrossAttnUpBlock2D`"""
|
99
|
+
|
100
|
+
def __init__(self, ctrl_to_base: nn.ModuleList):
|
101
|
+
super().__init__()
|
102
|
+
self.ctrl_to_base = ctrl_to_base
|
103
|
+
|
104
|
+
|
105
|
+
def get_down_block_adapter(
|
106
|
+
base_in_channels: int,
|
107
|
+
base_out_channels: int,
|
108
|
+
ctrl_in_channels: int,
|
109
|
+
ctrl_out_channels: int,
|
110
|
+
temb_channels: int,
|
111
|
+
max_norm_num_groups: Optional[int] = 32,
|
112
|
+
has_crossattn=True,
|
113
|
+
transformer_layers_per_block: Optional[Union[int, Tuple[int]]] = 1,
|
114
|
+
num_attention_heads: Optional[int] = 1,
|
115
|
+
cross_attention_dim: Optional[int] = 1024,
|
116
|
+
add_downsample: bool = True,
|
117
|
+
upcast_attention: Optional[bool] = False,
|
118
|
+
use_linear_projection: Optional[bool] = True,
|
119
|
+
):
|
120
|
+
num_layers = 2 # only support sd + sdxl
|
121
|
+
|
122
|
+
resnets = []
|
123
|
+
attentions = []
|
124
|
+
ctrl_to_base = []
|
125
|
+
base_to_ctrl = []
|
126
|
+
|
127
|
+
if isinstance(transformer_layers_per_block, int):
|
128
|
+
transformer_layers_per_block = [transformer_layers_per_block] * num_layers
|
129
|
+
|
130
|
+
for i in range(num_layers):
|
131
|
+
base_in_channels = base_in_channels if i == 0 else base_out_channels
|
132
|
+
ctrl_in_channels = ctrl_in_channels if i == 0 else ctrl_out_channels
|
133
|
+
|
134
|
+
# Before the resnet/attention application, information is concatted from base to control.
|
135
|
+
# Concat doesn't require change in number of channels
|
136
|
+
base_to_ctrl.append(make_zero_conv(base_in_channels, base_in_channels))
|
137
|
+
|
138
|
+
resnets.append(
|
139
|
+
ResnetBlock2D(
|
140
|
+
in_channels=ctrl_in_channels + base_in_channels, # information from base is concatted to ctrl
|
141
|
+
out_channels=ctrl_out_channels,
|
142
|
+
temb_channels=temb_channels,
|
143
|
+
groups=find_largest_factor(ctrl_in_channels + base_in_channels, max_factor=max_norm_num_groups),
|
144
|
+
groups_out=find_largest_factor(ctrl_out_channels, max_factor=max_norm_num_groups),
|
145
|
+
eps=1e-5,
|
146
|
+
)
|
147
|
+
)
|
148
|
+
|
149
|
+
if has_crossattn:
|
150
|
+
attentions.append(
|
151
|
+
Transformer2DModel(
|
152
|
+
num_attention_heads,
|
153
|
+
ctrl_out_channels // num_attention_heads,
|
154
|
+
in_channels=ctrl_out_channels,
|
155
|
+
num_layers=transformer_layers_per_block[i],
|
156
|
+
cross_attention_dim=cross_attention_dim,
|
157
|
+
use_linear_projection=use_linear_projection,
|
158
|
+
upcast_attention=upcast_attention,
|
159
|
+
norm_num_groups=find_largest_factor(ctrl_out_channels, max_factor=max_norm_num_groups),
|
160
|
+
)
|
161
|
+
)
|
162
|
+
|
163
|
+
# After the resnet/attention application, information is added from control to base
|
164
|
+
# Addition requires change in number of channels
|
165
|
+
ctrl_to_base.append(make_zero_conv(ctrl_out_channels, base_out_channels))
|
166
|
+
|
167
|
+
if add_downsample:
|
168
|
+
# Before the downsampler application, information is concatted from base to control
|
169
|
+
# Concat doesn't require change in number of channels
|
170
|
+
base_to_ctrl.append(make_zero_conv(base_out_channels, base_out_channels))
|
171
|
+
|
172
|
+
downsamplers = Downsample2D(
|
173
|
+
ctrl_out_channels + base_out_channels, use_conv=True, out_channels=ctrl_out_channels, name="op"
|
174
|
+
)
|
175
|
+
|
176
|
+
# After the downsampler application, information is added from control to base
|
177
|
+
# Addition requires change in number of channels
|
178
|
+
ctrl_to_base.append(make_zero_conv(ctrl_out_channels, base_out_channels))
|
179
|
+
else:
|
180
|
+
downsamplers = None
|
181
|
+
|
182
|
+
down_block_components = DownBlockControlNetXSAdapter(
|
183
|
+
resnets=nn.ModuleList(resnets),
|
184
|
+
base_to_ctrl=nn.ModuleList(base_to_ctrl),
|
185
|
+
ctrl_to_base=nn.ModuleList(ctrl_to_base),
|
186
|
+
)
|
187
|
+
|
188
|
+
if has_crossattn:
|
189
|
+
down_block_components.attentions = nn.ModuleList(attentions)
|
190
|
+
if downsamplers is not None:
|
191
|
+
down_block_components.downsamplers = downsamplers
|
192
|
+
|
193
|
+
return down_block_components
|
194
|
+
|
195
|
+
|
196
|
+
def get_mid_block_adapter(
|
197
|
+
base_channels: int,
|
198
|
+
ctrl_channels: int,
|
199
|
+
temb_channels: Optional[int] = None,
|
200
|
+
max_norm_num_groups: Optional[int] = 32,
|
201
|
+
transformer_layers_per_block: int = 1,
|
202
|
+
num_attention_heads: Optional[int] = 1,
|
203
|
+
cross_attention_dim: Optional[int] = 1024,
|
204
|
+
upcast_attention: bool = False,
|
205
|
+
use_linear_projection: bool = True,
|
206
|
+
):
|
207
|
+
# Before the midblock application, information is concatted from base to control.
|
208
|
+
# Concat doesn't require change in number of channels
|
209
|
+
base_to_ctrl = make_zero_conv(base_channels, base_channels)
|
210
|
+
|
211
|
+
midblock = UNetMidBlock2DCrossAttn(
|
212
|
+
transformer_layers_per_block=transformer_layers_per_block,
|
213
|
+
in_channels=ctrl_channels + base_channels,
|
214
|
+
out_channels=ctrl_channels,
|
215
|
+
temb_channels=temb_channels,
|
216
|
+
# number or norm groups must divide both in_channels and out_channels
|
217
|
+
resnet_groups=find_largest_factor(gcd(ctrl_channels, ctrl_channels + base_channels), max_norm_num_groups),
|
218
|
+
cross_attention_dim=cross_attention_dim,
|
219
|
+
num_attention_heads=num_attention_heads,
|
220
|
+
use_linear_projection=use_linear_projection,
|
221
|
+
upcast_attention=upcast_attention,
|
222
|
+
)
|
223
|
+
|
224
|
+
# After the midblock application, information is added from control to base
|
225
|
+
# Addition requires change in number of channels
|
226
|
+
ctrl_to_base = make_zero_conv(ctrl_channels, base_channels)
|
227
|
+
|
228
|
+
return MidBlockControlNetXSAdapter(base_to_ctrl=base_to_ctrl, midblock=midblock, ctrl_to_base=ctrl_to_base)
|
229
|
+
|
230
|
+
|
231
|
+
def get_up_block_adapter(
|
232
|
+
out_channels: int,
|
233
|
+
prev_output_channel: int,
|
234
|
+
ctrl_skip_channels: List[int],
|
235
|
+
):
|
236
|
+
ctrl_to_base = []
|
237
|
+
num_layers = 3 # only support sd + sdxl
|
238
|
+
for i in range(num_layers):
|
239
|
+
resnet_in_channels = prev_output_channel if i == 0 else out_channels
|
240
|
+
ctrl_to_base.append(make_zero_conv(ctrl_skip_channels[i], resnet_in_channels))
|
241
|
+
|
242
|
+
return UpBlockControlNetXSAdapter(ctrl_to_base=nn.ModuleList(ctrl_to_base))
|
243
|
+
|
244
|
+
|
245
|
+
class ControlNetXSAdapter(ModelMixin, ConfigMixin):
|
246
|
+
r"""
|
247
|
+
A `ControlNetXSAdapter` model. To use it, pass it into a `UNetControlNetXSModel` (together with a
|
248
|
+
`UNet2DConditionModel` base model).
|
249
|
+
|
250
|
+
This model inherits from [`ModelMixin`] and [`ConfigMixin`]. Check the superclass documentation for it's generic
|
251
|
+
methods implemented for all models (such as downloading or saving).
|
252
|
+
|
253
|
+
Like `UNetControlNetXSModel`, `ControlNetXSAdapter` is compatible with StableDiffusion and StableDiffusion-XL. It's
|
254
|
+
default parameters are compatible with StableDiffusion.
|
255
|
+
|
256
|
+
Parameters:
|
257
|
+
conditioning_channels (`int`, defaults to 3):
|
258
|
+
Number of channels of conditioning input (e.g. an image)
|
259
|
+
conditioning_channel_order (`str`, defaults to `"rgb"`):
|
260
|
+
The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
|
261
|
+
conditioning_embedding_out_channels (`tuple[int]`, defaults to `(16, 32, 96, 256)`):
|
262
|
+
The tuple of output channels for each block in the `controlnet_cond_embedding` layer.
|
263
|
+
time_embedding_mix (`float`, defaults to 1.0):
|
264
|
+
If 0, then only the control adapters's time embedding is used. If 1, then only the base unet's time
|
265
|
+
embedding is used. Otherwise, both are combined.
|
266
|
+
learn_time_embedding (`bool`, defaults to `False`):
|
267
|
+
Whether a time embedding should be learned. If yes, `UNetControlNetXSModel` will combine the time
|
268
|
+
embeddings of the base model and the control adapter. If no, `UNetControlNetXSModel` will use the base
|
269
|
+
model's time embedding.
|
270
|
+
num_attention_heads (`list[int]`, defaults to `[4]`):
|
271
|
+
The number of attention heads.
|
272
|
+
block_out_channels (`list[int]`, defaults to `[4, 8, 16, 16]`):
|
273
|
+
The tuple of output channels for each block.
|
274
|
+
base_block_out_channels (`list[int]`, defaults to `[320, 640, 1280, 1280]`):
|
275
|
+
The tuple of output channels for each block in the base unet.
|
276
|
+
cross_attention_dim (`int`, defaults to 1024):
|
277
|
+
The dimension of the cross attention features.
|
278
|
+
down_block_types (`list[str]`, defaults to `["CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D"]`):
|
279
|
+
The tuple of downsample blocks to use.
|
280
|
+
sample_size (`int`, defaults to 96):
|
281
|
+
Height and width of input/output sample.
|
282
|
+
transformer_layers_per_block (`Union[int, Tuple[int]]`, defaults to 1):
|
283
|
+
The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
|
284
|
+
[`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
|
285
|
+
upcast_attention (`bool`, defaults to `True`):
|
286
|
+
Whether the attention computation should always be upcasted.
|
287
|
+
max_norm_num_groups (`int`, defaults to 32):
|
288
|
+
Maximum number of groups in group normal. The actual number will be the largest divisor of the respective
|
289
|
+
channels, that is <= max_norm_num_groups.
|
290
|
+
"""
|
291
|
+
|
292
|
+
@register_to_config
|
293
|
+
def __init__(
|
294
|
+
self,
|
295
|
+
conditioning_channels: int = 3,
|
296
|
+
conditioning_channel_order: str = "rgb",
|
297
|
+
conditioning_embedding_out_channels: Tuple[int] = (16, 32, 96, 256),
|
298
|
+
time_embedding_mix: float = 1.0,
|
299
|
+
learn_time_embedding: bool = False,
|
300
|
+
num_attention_heads: Union[int, Tuple[int]] = 4,
|
301
|
+
block_out_channels: Tuple[int] = (4, 8, 16, 16),
|
302
|
+
base_block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
|
303
|
+
cross_attention_dim: int = 1024,
|
304
|
+
down_block_types: Tuple[str] = (
|
305
|
+
"CrossAttnDownBlock2D",
|
306
|
+
"CrossAttnDownBlock2D",
|
307
|
+
"CrossAttnDownBlock2D",
|
308
|
+
"DownBlock2D",
|
309
|
+
),
|
310
|
+
sample_size: Optional[int] = 96,
|
311
|
+
transformer_layers_per_block: Union[int, Tuple[int]] = 1,
|
312
|
+
upcast_attention: bool = True,
|
313
|
+
max_norm_num_groups: int = 32,
|
314
|
+
use_linear_projection: bool = True,
|
315
|
+
):
|
316
|
+
super().__init__()
|
317
|
+
|
318
|
+
time_embedding_input_dim = base_block_out_channels[0]
|
319
|
+
time_embedding_dim = base_block_out_channels[0] * 4
|
320
|
+
|
321
|
+
# Check inputs
|
322
|
+
if conditioning_channel_order not in ["rgb", "bgr"]:
|
323
|
+
raise ValueError(f"unknown `conditioning_channel_order`: {conditioning_channel_order}")
|
324
|
+
|
325
|
+
if len(block_out_channels) != len(down_block_types):
|
326
|
+
raise ValueError(
|
327
|
+
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}."
|
328
|
+
)
|
329
|
+
|
330
|
+
if not isinstance(transformer_layers_per_block, (list, tuple)):
|
331
|
+
transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
|
332
|
+
if not isinstance(cross_attention_dim, (list, tuple)):
|
333
|
+
cross_attention_dim = [cross_attention_dim] * len(down_block_types)
|
334
|
+
# see https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 for why `ControlNetXSAdapter` takes `num_attention_heads` instead of `attention_head_dim`
|
335
|
+
if not isinstance(num_attention_heads, (list, tuple)):
|
336
|
+
num_attention_heads = [num_attention_heads] * len(down_block_types)
|
337
|
+
|
338
|
+
if len(num_attention_heads) != len(down_block_types):
|
339
|
+
raise ValueError(
|
340
|
+
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}."
|
341
|
+
)
|
342
|
+
|
343
|
+
# 5 - Create conditioning hint embedding
|
344
|
+
self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
|
345
|
+
conditioning_embedding_channels=block_out_channels[0],
|
346
|
+
block_out_channels=conditioning_embedding_out_channels,
|
347
|
+
conditioning_channels=conditioning_channels,
|
348
|
+
)
|
349
|
+
|
350
|
+
# time
|
351
|
+
if learn_time_embedding:
|
352
|
+
self.time_embedding = TimestepEmbedding(time_embedding_input_dim, time_embedding_dim)
|
353
|
+
else:
|
354
|
+
self.time_embedding = None
|
355
|
+
|
356
|
+
self.down_blocks = nn.ModuleList([])
|
357
|
+
self.up_connections = nn.ModuleList([])
|
358
|
+
|
359
|
+
# input
|
360
|
+
self.conv_in = nn.Conv2d(4, block_out_channels[0], kernel_size=3, padding=1)
|
361
|
+
self.control_to_base_for_conv_in = make_zero_conv(block_out_channels[0], base_block_out_channels[0])
|
362
|
+
|
363
|
+
# down
|
364
|
+
base_out_channels = base_block_out_channels[0]
|
365
|
+
ctrl_out_channels = block_out_channels[0]
|
366
|
+
for i, down_block_type in enumerate(down_block_types):
|
367
|
+
base_in_channels = base_out_channels
|
368
|
+
base_out_channels = base_block_out_channels[i]
|
369
|
+
ctrl_in_channels = ctrl_out_channels
|
370
|
+
ctrl_out_channels = block_out_channels[i]
|
371
|
+
has_crossattn = "CrossAttn" in down_block_type
|
372
|
+
is_final_block = i == len(down_block_types) - 1
|
373
|
+
|
374
|
+
self.down_blocks.append(
|
375
|
+
get_down_block_adapter(
|
376
|
+
base_in_channels=base_in_channels,
|
377
|
+
base_out_channels=base_out_channels,
|
378
|
+
ctrl_in_channels=ctrl_in_channels,
|
379
|
+
ctrl_out_channels=ctrl_out_channels,
|
380
|
+
temb_channels=time_embedding_dim,
|
381
|
+
max_norm_num_groups=max_norm_num_groups,
|
382
|
+
has_crossattn=has_crossattn,
|
383
|
+
transformer_layers_per_block=transformer_layers_per_block[i],
|
384
|
+
num_attention_heads=num_attention_heads[i],
|
385
|
+
cross_attention_dim=cross_attention_dim[i],
|
386
|
+
add_downsample=not is_final_block,
|
387
|
+
upcast_attention=upcast_attention,
|
388
|
+
use_linear_projection=use_linear_projection,
|
389
|
+
)
|
390
|
+
)
|
391
|
+
|
392
|
+
# mid
|
393
|
+
self.mid_block = get_mid_block_adapter(
|
394
|
+
base_channels=base_block_out_channels[-1],
|
395
|
+
ctrl_channels=block_out_channels[-1],
|
396
|
+
temb_channels=time_embedding_dim,
|
397
|
+
transformer_layers_per_block=transformer_layers_per_block[-1],
|
398
|
+
num_attention_heads=num_attention_heads[-1],
|
399
|
+
cross_attention_dim=cross_attention_dim[-1],
|
400
|
+
upcast_attention=upcast_attention,
|
401
|
+
use_linear_projection=use_linear_projection,
|
402
|
+
)
|
403
|
+
|
404
|
+
# up
|
405
|
+
# The skip connection channels are the output of the conv_in and of all the down subblocks
|
406
|
+
ctrl_skip_channels = [block_out_channels[0]]
|
407
|
+
for i, out_channels in enumerate(block_out_channels):
|
408
|
+
number_of_subblocks = (
|
409
|
+
3 if i < len(block_out_channels) - 1 else 2
|
410
|
+
) # every block has 3 subblocks, except last one, which has 2 as it has no downsampler
|
411
|
+
ctrl_skip_channels.extend([out_channels] * number_of_subblocks)
|
412
|
+
|
413
|
+
reversed_base_block_out_channels = list(reversed(base_block_out_channels))
|
414
|
+
|
415
|
+
base_out_channels = reversed_base_block_out_channels[0]
|
416
|
+
for i in range(len(down_block_types)):
|
417
|
+
prev_base_output_channel = base_out_channels
|
418
|
+
base_out_channels = reversed_base_block_out_channels[i]
|
419
|
+
ctrl_skip_channels_ = [ctrl_skip_channels.pop() for _ in range(3)]
|
420
|
+
|
421
|
+
self.up_connections.append(
|
422
|
+
get_up_block_adapter(
|
423
|
+
out_channels=base_out_channels,
|
424
|
+
prev_output_channel=prev_base_output_channel,
|
425
|
+
ctrl_skip_channels=ctrl_skip_channels_,
|
426
|
+
)
|
427
|
+
)
|
428
|
+
|
429
|
+
@classmethod
|
430
|
+
def from_unet(
|
431
|
+
cls,
|
432
|
+
unet: UNet2DConditionModel,
|
433
|
+
size_ratio: Optional[float] = None,
|
434
|
+
block_out_channels: Optional[List[int]] = None,
|
435
|
+
num_attention_heads: Optional[List[int]] = None,
|
436
|
+
learn_time_embedding: bool = False,
|
437
|
+
time_embedding_mix: int = 1.0,
|
438
|
+
conditioning_channels: int = 3,
|
439
|
+
conditioning_channel_order: str = "rgb",
|
440
|
+
conditioning_embedding_out_channels: Tuple[int] = (16, 32, 96, 256),
|
441
|
+
):
|
442
|
+
r"""
|
443
|
+
Instantiate a [`ControlNetXSAdapter`] from a [`UNet2DConditionModel`].
|
444
|
+
|
445
|
+
Parameters:
|
446
|
+
unet (`UNet2DConditionModel`):
|
447
|
+
The UNet model we want to control. The dimensions of the ControlNetXSAdapter will be adapted to it.
|
448
|
+
size_ratio (float, *optional*, defaults to `None`):
|
449
|
+
When given, block_out_channels is set to a fraction of the base model's block_out_channels. Either this
|
450
|
+
or `block_out_channels` must be given.
|
451
|
+
block_out_channels (`List[int]`, *optional*, defaults to `None`):
|
452
|
+
Down blocks output channels in control model. Either this or `size_ratio` must be given.
|
453
|
+
num_attention_heads (`List[int]`, *optional*, defaults to `None`):
|
454
|
+
The dimension of the attention heads. The naming seems a bit confusing and it is, see
|
455
|
+
https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 for why.
|
456
|
+
learn_time_embedding (`bool`, defaults to `False`):
|
457
|
+
Whether the `ControlNetXSAdapter` should learn a time embedding.
|
458
|
+
time_embedding_mix (`float`, defaults to 1.0):
|
459
|
+
If 0, then only the control adapter's time embedding is used. If 1, then only the base unet's time
|
460
|
+
embedding is used. Otherwise, both are combined.
|
461
|
+
conditioning_channels (`int`, defaults to 3):
|
462
|
+
Number of channels of conditioning input (e.g. an image)
|
463
|
+
conditioning_channel_order (`str`, defaults to `"rgb"`):
|
464
|
+
The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
|
465
|
+
conditioning_embedding_out_channels (`Tuple[int]`, defaults to `(16, 32, 96, 256)`):
|
466
|
+
The tuple of output channel for each block in the `controlnet_cond_embedding` layer.
|
467
|
+
"""
|
468
|
+
|
469
|
+
# Check input
|
470
|
+
fixed_size = block_out_channels is not None
|
471
|
+
relative_size = size_ratio is not None
|
472
|
+
if not (fixed_size ^ relative_size):
|
473
|
+
raise ValueError(
|
474
|
+
"Pass exactly one of `block_out_channels` (for absolute sizing) or `size_ratio` (for relative sizing)."
|
475
|
+
)
|
476
|
+
|
477
|
+
# Create model
|
478
|
+
block_out_channels = block_out_channels or [int(b * size_ratio) for b in unet.config.block_out_channels]
|
479
|
+
if num_attention_heads is None:
|
480
|
+
# The naming seems a bit confusing and it is, see https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 for why.
|
481
|
+
num_attention_heads = unet.config.attention_head_dim
|
482
|
+
|
483
|
+
model = cls(
|
484
|
+
conditioning_channels=conditioning_channels,
|
485
|
+
conditioning_channel_order=conditioning_channel_order,
|
486
|
+
conditioning_embedding_out_channels=conditioning_embedding_out_channels,
|
487
|
+
time_embedding_mix=time_embedding_mix,
|
488
|
+
learn_time_embedding=learn_time_embedding,
|
489
|
+
num_attention_heads=num_attention_heads,
|
490
|
+
block_out_channels=block_out_channels,
|
491
|
+
base_block_out_channels=unet.config.block_out_channels,
|
492
|
+
cross_attention_dim=unet.config.cross_attention_dim,
|
493
|
+
down_block_types=unet.config.down_block_types,
|
494
|
+
sample_size=unet.config.sample_size,
|
495
|
+
transformer_layers_per_block=unet.config.transformer_layers_per_block,
|
496
|
+
upcast_attention=unet.config.upcast_attention,
|
497
|
+
max_norm_num_groups=unet.config.norm_num_groups,
|
498
|
+
use_linear_projection=unet.config.use_linear_projection,
|
499
|
+
)
|
500
|
+
|
501
|
+
# ensure that the ControlNetXSAdapter is the same dtype as the UNet2DConditionModel
|
502
|
+
model.to(unet.dtype)
|
503
|
+
|
504
|
+
return model
|
505
|
+
|
506
|
+
def forward(self, *args, **kwargs):
|
507
|
+
raise ValueError(
|
508
|
+
"A ControlNetXSAdapter cannot be run by itself. Use it together with a UNet2DConditionModel to instantiate a UNetControlNetXSModel."
|
509
|
+
)
|
510
|
+
|
511
|
+
|
512
|
+
class UNetControlNetXSModel(ModelMixin, ConfigMixin):
|
513
|
+
r"""
|
514
|
+
A UNet fused with a ControlNet-XS adapter model
|
515
|
+
|
516
|
+
This model inherits from [`ModelMixin`] and [`ConfigMixin`]. Check the superclass documentation for it's generic
|
517
|
+
methods implemented for all models (such as downloading or saving).
|
518
|
+
|
519
|
+
`UNetControlNetXSModel` is compatible with StableDiffusion and StableDiffusion-XL. It's default parameters are
|
520
|
+
compatible with StableDiffusion.
|
521
|
+
|
522
|
+
It's parameters are either passed to the underlying `UNet2DConditionModel` or used exactly like in
|
523
|
+
`ControlNetXSAdapter` . See their documentation for details.
|
524
|
+
"""
|
525
|
+
|
526
|
+
_supports_gradient_checkpointing = True
|
527
|
+
|
528
|
+
@register_to_config
|
529
|
+
def __init__(
|
530
|
+
self,
|
531
|
+
# unet configs
|
532
|
+
sample_size: Optional[int] = 96,
|
533
|
+
down_block_types: Tuple[str] = (
|
534
|
+
"CrossAttnDownBlock2D",
|
535
|
+
"CrossAttnDownBlock2D",
|
536
|
+
"CrossAttnDownBlock2D",
|
537
|
+
"DownBlock2D",
|
538
|
+
),
|
539
|
+
up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
|
540
|
+
block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
|
541
|
+
norm_num_groups: Optional[int] = 32,
|
542
|
+
cross_attention_dim: Union[int, Tuple[int]] = 1024,
|
543
|
+
transformer_layers_per_block: Union[int, Tuple[int]] = 1,
|
544
|
+
num_attention_heads: Union[int, Tuple[int]] = 8,
|
545
|
+
addition_embed_type: Optional[str] = None,
|
546
|
+
addition_time_embed_dim: Optional[int] = None,
|
547
|
+
upcast_attention: bool = True,
|
548
|
+
use_linear_projection: bool = True,
|
549
|
+
time_cond_proj_dim: Optional[int] = None,
|
550
|
+
projection_class_embeddings_input_dim: Optional[int] = None,
|
551
|
+
# additional controlnet configs
|
552
|
+
time_embedding_mix: float = 1.0,
|
553
|
+
ctrl_conditioning_channels: int = 3,
|
554
|
+
ctrl_conditioning_embedding_out_channels: Tuple[int] = (16, 32, 96, 256),
|
555
|
+
ctrl_conditioning_channel_order: str = "rgb",
|
556
|
+
ctrl_learn_time_embedding: bool = False,
|
557
|
+
ctrl_block_out_channels: Tuple[int] = (4, 8, 16, 16),
|
558
|
+
ctrl_num_attention_heads: Union[int, Tuple[int]] = 4,
|
559
|
+
ctrl_max_norm_num_groups: int = 32,
|
560
|
+
):
|
561
|
+
super().__init__()
|
562
|
+
|
563
|
+
if time_embedding_mix < 0 or time_embedding_mix > 1:
|
564
|
+
raise ValueError("`time_embedding_mix` needs to be between 0 and 1.")
|
565
|
+
if time_embedding_mix < 1 and not ctrl_learn_time_embedding:
|
566
|
+
raise ValueError("To use `time_embedding_mix` < 1, `ctrl_learn_time_embedding` must be `True`")
|
567
|
+
|
568
|
+
if addition_embed_type is not None and addition_embed_type != "text_time":
|
569
|
+
raise ValueError(
|
570
|
+
"As `UNetControlNetXSModel` currently only supports StableDiffusion and StableDiffusion-XL, `addition_embed_type` must be `None` or `'text_time'`."
|
571
|
+
)
|
572
|
+
|
573
|
+
if not isinstance(transformer_layers_per_block, (list, tuple)):
|
574
|
+
transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
|
575
|
+
if not isinstance(cross_attention_dim, (list, tuple)):
|
576
|
+
cross_attention_dim = [cross_attention_dim] * len(down_block_types)
|
577
|
+
if not isinstance(num_attention_heads, (list, tuple)):
|
578
|
+
num_attention_heads = [num_attention_heads] * len(down_block_types)
|
579
|
+
if not isinstance(ctrl_num_attention_heads, (list, tuple)):
|
580
|
+
ctrl_num_attention_heads = [ctrl_num_attention_heads] * len(down_block_types)
|
581
|
+
|
582
|
+
base_num_attention_heads = num_attention_heads
|
583
|
+
|
584
|
+
self.in_channels = 4
|
585
|
+
|
586
|
+
# # Input
|
587
|
+
self.base_conv_in = nn.Conv2d(4, block_out_channels[0], kernel_size=3, padding=1)
|
588
|
+
self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
|
589
|
+
conditioning_embedding_channels=ctrl_block_out_channels[0],
|
590
|
+
block_out_channels=ctrl_conditioning_embedding_out_channels,
|
591
|
+
conditioning_channels=ctrl_conditioning_channels,
|
592
|
+
)
|
593
|
+
self.ctrl_conv_in = nn.Conv2d(4, ctrl_block_out_channels[0], kernel_size=3, padding=1)
|
594
|
+
self.control_to_base_for_conv_in = make_zero_conv(ctrl_block_out_channels[0], block_out_channels[0])
|
595
|
+
|
596
|
+
# # Time
|
597
|
+
time_embed_input_dim = block_out_channels[0]
|
598
|
+
time_embed_dim = block_out_channels[0] * 4
|
599
|
+
|
600
|
+
self.base_time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos=True, downscale_freq_shift=0)
|
601
|
+
self.base_time_embedding = TimestepEmbedding(
|
602
|
+
time_embed_input_dim,
|
603
|
+
time_embed_dim,
|
604
|
+
cond_proj_dim=time_cond_proj_dim,
|
605
|
+
)
|
606
|
+
if ctrl_learn_time_embedding:
|
607
|
+
self.ctrl_time_embedding = TimestepEmbedding(
|
608
|
+
in_channels=time_embed_input_dim, time_embed_dim=time_embed_dim
|
609
|
+
)
|
610
|
+
else:
|
611
|
+
self.ctrl_time_embedding = None
|
612
|
+
|
613
|
+
if addition_embed_type is None:
|
614
|
+
self.base_add_time_proj = None
|
615
|
+
self.base_add_embedding = None
|
616
|
+
else:
|
617
|
+
self.base_add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
|
618
|
+
self.base_add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
|
619
|
+
|
620
|
+
# # Create down blocks
|
621
|
+
down_blocks = []
|
622
|
+
base_out_channels = block_out_channels[0]
|
623
|
+
ctrl_out_channels = ctrl_block_out_channels[0]
|
624
|
+
for i, down_block_type in enumerate(down_block_types):
|
625
|
+
base_in_channels = base_out_channels
|
626
|
+
base_out_channels = block_out_channels[i]
|
627
|
+
ctrl_in_channels = ctrl_out_channels
|
628
|
+
ctrl_out_channels = ctrl_block_out_channels[i]
|
629
|
+
has_crossattn = "CrossAttn" in down_block_type
|
630
|
+
is_final_block = i == len(down_block_types) - 1
|
631
|
+
|
632
|
+
down_blocks.append(
|
633
|
+
ControlNetXSCrossAttnDownBlock2D(
|
634
|
+
base_in_channels=base_in_channels,
|
635
|
+
base_out_channels=base_out_channels,
|
636
|
+
ctrl_in_channels=ctrl_in_channels,
|
637
|
+
ctrl_out_channels=ctrl_out_channels,
|
638
|
+
temb_channels=time_embed_dim,
|
639
|
+
norm_num_groups=norm_num_groups,
|
640
|
+
ctrl_max_norm_num_groups=ctrl_max_norm_num_groups,
|
641
|
+
has_crossattn=has_crossattn,
|
642
|
+
transformer_layers_per_block=transformer_layers_per_block[i],
|
643
|
+
base_num_attention_heads=base_num_attention_heads[i],
|
644
|
+
ctrl_num_attention_heads=ctrl_num_attention_heads[i],
|
645
|
+
cross_attention_dim=cross_attention_dim[i],
|
646
|
+
add_downsample=not is_final_block,
|
647
|
+
upcast_attention=upcast_attention,
|
648
|
+
use_linear_projection=use_linear_projection,
|
649
|
+
)
|
650
|
+
)
|
651
|
+
|
652
|
+
# # Create mid block
|
653
|
+
self.mid_block = ControlNetXSCrossAttnMidBlock2D(
|
654
|
+
base_channels=block_out_channels[-1],
|
655
|
+
ctrl_channels=ctrl_block_out_channels[-1],
|
656
|
+
temb_channels=time_embed_dim,
|
657
|
+
norm_num_groups=norm_num_groups,
|
658
|
+
ctrl_max_norm_num_groups=ctrl_max_norm_num_groups,
|
659
|
+
transformer_layers_per_block=transformer_layers_per_block[-1],
|
660
|
+
base_num_attention_heads=base_num_attention_heads[-1],
|
661
|
+
ctrl_num_attention_heads=ctrl_num_attention_heads[-1],
|
662
|
+
cross_attention_dim=cross_attention_dim[-1],
|
663
|
+
upcast_attention=upcast_attention,
|
664
|
+
use_linear_projection=use_linear_projection,
|
665
|
+
)
|
666
|
+
|
667
|
+
# # Create up blocks
|
668
|
+
up_blocks = []
|
669
|
+
rev_transformer_layers_per_block = list(reversed(transformer_layers_per_block))
|
670
|
+
rev_num_attention_heads = list(reversed(base_num_attention_heads))
|
671
|
+
rev_cross_attention_dim = list(reversed(cross_attention_dim))
|
672
|
+
|
673
|
+
# The skip connection channels are the output of the conv_in and of all the down subblocks
|
674
|
+
ctrl_skip_channels = [ctrl_block_out_channels[0]]
|
675
|
+
for i, out_channels in enumerate(ctrl_block_out_channels):
|
676
|
+
number_of_subblocks = (
|
677
|
+
3 if i < len(ctrl_block_out_channels) - 1 else 2
|
678
|
+
) # every block has 3 subblocks, except last one, which has 2 as it has no downsampler
|
679
|
+
ctrl_skip_channels.extend([out_channels] * number_of_subblocks)
|
680
|
+
|
681
|
+
reversed_block_out_channels = list(reversed(block_out_channels))
|
682
|
+
|
683
|
+
out_channels = reversed_block_out_channels[0]
|
684
|
+
for i, up_block_type in enumerate(up_block_types):
|
685
|
+
prev_output_channel = out_channels
|
686
|
+
out_channels = reversed_block_out_channels[i]
|
687
|
+
in_channels = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
|
688
|
+
ctrl_skip_channels_ = [ctrl_skip_channels.pop() for _ in range(3)]
|
689
|
+
|
690
|
+
has_crossattn = "CrossAttn" in up_block_type
|
691
|
+
is_final_block = i == len(block_out_channels) - 1
|
692
|
+
|
693
|
+
up_blocks.append(
|
694
|
+
ControlNetXSCrossAttnUpBlock2D(
|
695
|
+
in_channels=in_channels,
|
696
|
+
out_channels=out_channels,
|
697
|
+
prev_output_channel=prev_output_channel,
|
698
|
+
ctrl_skip_channels=ctrl_skip_channels_,
|
699
|
+
temb_channels=time_embed_dim,
|
700
|
+
resolution_idx=i,
|
701
|
+
has_crossattn=has_crossattn,
|
702
|
+
transformer_layers_per_block=rev_transformer_layers_per_block[i],
|
703
|
+
num_attention_heads=rev_num_attention_heads[i],
|
704
|
+
cross_attention_dim=rev_cross_attention_dim[i],
|
705
|
+
add_upsample=not is_final_block,
|
706
|
+
upcast_attention=upcast_attention,
|
707
|
+
norm_num_groups=norm_num_groups,
|
708
|
+
use_linear_projection=use_linear_projection,
|
709
|
+
)
|
710
|
+
)
|
711
|
+
|
712
|
+
self.down_blocks = nn.ModuleList(down_blocks)
|
713
|
+
self.up_blocks = nn.ModuleList(up_blocks)
|
714
|
+
|
715
|
+
self.base_conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups)
|
716
|
+
self.base_conv_act = nn.SiLU()
|
717
|
+
self.base_conv_out = nn.Conv2d(block_out_channels[0], 4, kernel_size=3, padding=1)
|
718
|
+
|
719
|
+
@classmethod
|
720
|
+
def from_unet(
|
721
|
+
cls,
|
722
|
+
unet: UNet2DConditionModel,
|
723
|
+
controlnet: Optional[ControlNetXSAdapter] = None,
|
724
|
+
size_ratio: Optional[float] = None,
|
725
|
+
ctrl_block_out_channels: Optional[List[float]] = None,
|
726
|
+
time_embedding_mix: Optional[float] = None,
|
727
|
+
ctrl_optional_kwargs: Optional[Dict] = None,
|
728
|
+
):
|
729
|
+
r"""
|
730
|
+
Instantiate a [`UNetControlNetXSModel`] from a [`UNet2DConditionModel`] and an optional [`ControlNetXSAdapter`]
|
731
|
+
.
|
732
|
+
|
733
|
+
Parameters:
|
734
|
+
unet (`UNet2DConditionModel`):
|
735
|
+
The UNet model we want to control.
|
736
|
+
controlnet (`ControlNetXSAdapter`):
|
737
|
+
The ConntrolNet-XS adapter with which the UNet will be fused. If none is given, a new ConntrolNet-XS
|
738
|
+
adapter will be created.
|
739
|
+
size_ratio (float, *optional*, defaults to `None`):
|
740
|
+
Used to contruct the controlnet if none is given. See [`ControlNetXSAdapter.from_unet`] for details.
|
741
|
+
ctrl_block_out_channels (`List[int]`, *optional*, defaults to `None`):
|
742
|
+
Used to contruct the controlnet if none is given. See [`ControlNetXSAdapter.from_unet`] for details,
|
743
|
+
where this parameter is called `block_out_channels`.
|
744
|
+
time_embedding_mix (`float`, *optional*, defaults to None):
|
745
|
+
Used to contruct the controlnet if none is given. See [`ControlNetXSAdapter.from_unet`] for details.
|
746
|
+
ctrl_optional_kwargs (`Dict`, *optional*, defaults to `None`):
|
747
|
+
Passed to the `init` of the new controlent if no controlent was given.
|
748
|
+
"""
|
749
|
+
if controlnet is None:
|
750
|
+
controlnet = ControlNetXSAdapter.from_unet(
|
751
|
+
unet, size_ratio, ctrl_block_out_channels, **ctrl_optional_kwargs
|
752
|
+
)
|
753
|
+
else:
|
754
|
+
if any(
|
755
|
+
o is not None for o in (size_ratio, ctrl_block_out_channels, time_embedding_mix, ctrl_optional_kwargs)
|
756
|
+
):
|
757
|
+
raise ValueError(
|
758
|
+
"When a controlnet is passed, none of these parameters should be passed: size_ratio, ctrl_block_out_channels, time_embedding_mix, ctrl_optional_kwargs."
|
759
|
+
)
|
760
|
+
|
761
|
+
# # get params
|
762
|
+
params_for_unet = [
|
763
|
+
"sample_size",
|
764
|
+
"down_block_types",
|
765
|
+
"up_block_types",
|
766
|
+
"block_out_channels",
|
767
|
+
"norm_num_groups",
|
768
|
+
"cross_attention_dim",
|
769
|
+
"transformer_layers_per_block",
|
770
|
+
"addition_embed_type",
|
771
|
+
"addition_time_embed_dim",
|
772
|
+
"upcast_attention",
|
773
|
+
"use_linear_projection",
|
774
|
+
"time_cond_proj_dim",
|
775
|
+
"projection_class_embeddings_input_dim",
|
776
|
+
]
|
777
|
+
params_for_unet = {k: v for k, v in unet.config.items() if k in params_for_unet}
|
778
|
+
# The naming seems a bit confusing and it is, see https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 for why.
|
779
|
+
params_for_unet["num_attention_heads"] = unet.config.attention_head_dim
|
780
|
+
|
781
|
+
params_for_controlnet = [
|
782
|
+
"conditioning_channels",
|
783
|
+
"conditioning_embedding_out_channels",
|
784
|
+
"conditioning_channel_order",
|
785
|
+
"learn_time_embedding",
|
786
|
+
"block_out_channels",
|
787
|
+
"num_attention_heads",
|
788
|
+
"max_norm_num_groups",
|
789
|
+
]
|
790
|
+
params_for_controlnet = {"ctrl_" + k: v for k, v in controlnet.config.items() if k in params_for_controlnet}
|
791
|
+
params_for_controlnet["time_embedding_mix"] = controlnet.config.time_embedding_mix
|
792
|
+
|
793
|
+
# # create model
|
794
|
+
model = cls.from_config({**params_for_unet, **params_for_controlnet})
|
795
|
+
|
796
|
+
# # load weights
|
797
|
+
# from unet
|
798
|
+
modules_from_unet = [
|
799
|
+
"time_embedding",
|
800
|
+
"conv_in",
|
801
|
+
"conv_norm_out",
|
802
|
+
"conv_out",
|
803
|
+
]
|
804
|
+
for m in modules_from_unet:
|
805
|
+
getattr(model, "base_" + m).load_state_dict(getattr(unet, m).state_dict())
|
806
|
+
|
807
|
+
optional_modules_from_unet = [
|
808
|
+
"add_time_proj",
|
809
|
+
"add_embedding",
|
810
|
+
]
|
811
|
+
for m in optional_modules_from_unet:
|
812
|
+
if hasattr(unet, m) and getattr(unet, m) is not None:
|
813
|
+
getattr(model, "base_" + m).load_state_dict(getattr(unet, m).state_dict())
|
814
|
+
|
815
|
+
# from controlnet
|
816
|
+
model.controlnet_cond_embedding.load_state_dict(controlnet.controlnet_cond_embedding.state_dict())
|
817
|
+
model.ctrl_conv_in.load_state_dict(controlnet.conv_in.state_dict())
|
818
|
+
if controlnet.time_embedding is not None:
|
819
|
+
model.ctrl_time_embedding.load_state_dict(controlnet.time_embedding.state_dict())
|
820
|
+
model.control_to_base_for_conv_in.load_state_dict(controlnet.control_to_base_for_conv_in.state_dict())
|
821
|
+
|
822
|
+
# from both
|
823
|
+
model.down_blocks = nn.ModuleList(
|
824
|
+
ControlNetXSCrossAttnDownBlock2D.from_modules(b, c)
|
825
|
+
for b, c in zip(unet.down_blocks, controlnet.down_blocks)
|
826
|
+
)
|
827
|
+
model.mid_block = ControlNetXSCrossAttnMidBlock2D.from_modules(unet.mid_block, controlnet.mid_block)
|
828
|
+
model.up_blocks = nn.ModuleList(
|
829
|
+
ControlNetXSCrossAttnUpBlock2D.from_modules(b, c)
|
830
|
+
for b, c in zip(unet.up_blocks, controlnet.up_connections)
|
831
|
+
)
|
832
|
+
|
833
|
+
# ensure that the UNetControlNetXSModel is the same dtype as the UNet2DConditionModel
|
834
|
+
model.to(unet.dtype)
|
835
|
+
|
836
|
+
return model
|
837
|
+
|
838
|
+
def freeze_unet_params(self) -> None:
|
839
|
+
"""Freeze the weights of the parts belonging to the base UNet2DConditionModel, and leave everything else unfrozen for fine
|
840
|
+
tuning."""
|
841
|
+
# Freeze everything
|
842
|
+
for param in self.parameters():
|
843
|
+
param.requires_grad = True
|
844
|
+
|
845
|
+
# Unfreeze ControlNetXSAdapter
|
846
|
+
base_parts = [
|
847
|
+
"base_time_proj",
|
848
|
+
"base_time_embedding",
|
849
|
+
"base_add_time_proj",
|
850
|
+
"base_add_embedding",
|
851
|
+
"base_conv_in",
|
852
|
+
"base_conv_norm_out",
|
853
|
+
"base_conv_act",
|
854
|
+
"base_conv_out",
|
855
|
+
]
|
856
|
+
base_parts = [getattr(self, part) for part in base_parts if getattr(self, part) is not None]
|
857
|
+
for part in base_parts:
|
858
|
+
for param in part.parameters():
|
859
|
+
param.requires_grad = False
|
860
|
+
|
861
|
+
for d in self.down_blocks:
|
862
|
+
d.freeze_base_params()
|
863
|
+
self.mid_block.freeze_base_params()
|
864
|
+
for u in self.up_blocks:
|
865
|
+
u.freeze_base_params()
|
866
|
+
|
867
|
+
def _set_gradient_checkpointing(self, module, value=False):
|
868
|
+
if hasattr(module, "gradient_checkpointing"):
|
869
|
+
module.gradient_checkpointing = value
|
870
|
+
|
871
|
+
@property
|
872
|
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
|
873
|
+
def attn_processors(self) -> Dict[str, AttentionProcessor]:
|
874
|
+
r"""
|
875
|
+
Returns:
|
876
|
+
`dict` of attention processors: A dictionary containing all attention processors used in the model with
|
877
|
+
indexed by its weight name.
|
878
|
+
"""
|
879
|
+
# set recursively
|
880
|
+
processors = {}
|
881
|
+
|
882
|
+
def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
|
883
|
+
if hasattr(module, "get_processor"):
|
884
|
+
processors[f"{name}.processor"] = module.get_processor()
|
885
|
+
|
886
|
+
for sub_name, child in module.named_children():
|
887
|
+
fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
|
888
|
+
|
889
|
+
return processors
|
890
|
+
|
891
|
+
for name, module in self.named_children():
|
892
|
+
fn_recursive_add_processors(name, module, processors)
|
893
|
+
|
894
|
+
return processors
|
895
|
+
|
896
|
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
|
897
|
+
def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
|
898
|
+
r"""
|
899
|
+
Sets the attention processor to use to compute attention.
|
900
|
+
|
901
|
+
Parameters:
|
902
|
+
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
|
903
|
+
The instantiated processor class or a dictionary of processor classes that will be set as the processor
|
904
|
+
for **all** `Attention` layers.
|
905
|
+
|
906
|
+
If `processor` is a dict, the key needs to define the path to the corresponding cross attention
|
907
|
+
processor. This is strongly recommended when setting trainable attention processors.
|
908
|
+
|
909
|
+
"""
|
910
|
+
count = len(self.attn_processors.keys())
|
911
|
+
|
912
|
+
if isinstance(processor, dict) and len(processor) != count:
|
913
|
+
raise ValueError(
|
914
|
+
f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
|
915
|
+
f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
|
916
|
+
)
|
917
|
+
|
918
|
+
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
|
919
|
+
if hasattr(module, "set_processor"):
|
920
|
+
if not isinstance(processor, dict):
|
921
|
+
module.set_processor(processor)
|
922
|
+
else:
|
923
|
+
module.set_processor(processor.pop(f"{name}.processor"))
|
924
|
+
|
925
|
+
for sub_name, child in module.named_children():
|
926
|
+
fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
|
927
|
+
|
928
|
+
for name, module in self.named_children():
|
929
|
+
fn_recursive_attn_processor(name, module, processor)
|
930
|
+
|
931
|
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
|
932
|
+
def set_default_attn_processor(self):
|
933
|
+
"""
|
934
|
+
Disables custom attention processors and sets the default attention implementation.
|
935
|
+
"""
|
936
|
+
if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
|
937
|
+
processor = AttnAddedKVProcessor()
|
938
|
+
elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
|
939
|
+
processor = AttnProcessor()
|
940
|
+
else:
|
941
|
+
raise ValueError(
|
942
|
+
f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
|
943
|
+
)
|
944
|
+
|
945
|
+
self.set_attn_processor(processor)
|
946
|
+
|
947
|
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.enable_freeu
|
948
|
+
def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
|
949
|
+
r"""Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497.
|
950
|
+
|
951
|
+
The suffixes after the scaling factors represent the stage blocks where they are being applied.
|
952
|
+
|
953
|
+
Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that
|
954
|
+
are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
|
955
|
+
|
956
|
+
Args:
|
957
|
+
s1 (`float`):
|
958
|
+
Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
|
959
|
+
mitigate the "oversmoothing effect" in the enhanced denoising process.
|
960
|
+
s2 (`float`):
|
961
|
+
Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
|
962
|
+
mitigate the "oversmoothing effect" in the enhanced denoising process.
|
963
|
+
b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
|
964
|
+
b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
|
965
|
+
"""
|
966
|
+
for i, upsample_block in enumerate(self.up_blocks):
|
967
|
+
setattr(upsample_block, "s1", s1)
|
968
|
+
setattr(upsample_block, "s2", s2)
|
969
|
+
setattr(upsample_block, "b1", b1)
|
970
|
+
setattr(upsample_block, "b2", b2)
|
971
|
+
|
972
|
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.disable_freeu
|
973
|
+
def disable_freeu(self):
|
974
|
+
"""Disables the FreeU mechanism."""
|
975
|
+
freeu_keys = {"s1", "s2", "b1", "b2"}
|
976
|
+
for i, upsample_block in enumerate(self.up_blocks):
|
977
|
+
for k in freeu_keys:
|
978
|
+
if hasattr(upsample_block, k) or getattr(upsample_block, k, None) is not None:
|
979
|
+
setattr(upsample_block, k, None)
|
980
|
+
|
981
|
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections
|
982
|
+
def fuse_qkv_projections(self):
|
983
|
+
"""
|
984
|
+
Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
|
985
|
+
are fused. For cross-attention modules, key and value projection matrices are fused.
|
986
|
+
|
987
|
+
<Tip warning={true}>
|
988
|
+
|
989
|
+
This API is 🧪 experimental.
|
990
|
+
|
991
|
+
</Tip>
|
992
|
+
"""
|
993
|
+
self.original_attn_processors = None
|
994
|
+
|
995
|
+
for _, attn_processor in self.attn_processors.items():
|
996
|
+
if "Added" in str(attn_processor.__class__.__name__):
|
997
|
+
raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
|
998
|
+
|
999
|
+
self.original_attn_processors = self.attn_processors
|
1000
|
+
|
1001
|
+
for module in self.modules():
|
1002
|
+
if isinstance(module, Attention):
|
1003
|
+
module.fuse_projections(fuse=True)
|
1004
|
+
|
1005
|
+
self.set_attn_processor(FusedAttnProcessor2_0())
|
1006
|
+
|
1007
|
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
|
1008
|
+
def unfuse_qkv_projections(self):
|
1009
|
+
"""Disables the fused QKV projection if enabled.
|
1010
|
+
|
1011
|
+
<Tip warning={true}>
|
1012
|
+
|
1013
|
+
This API is 🧪 experimental.
|
1014
|
+
|
1015
|
+
</Tip>
|
1016
|
+
|
1017
|
+
"""
|
1018
|
+
if self.original_attn_processors is not None:
|
1019
|
+
self.set_attn_processor(self.original_attn_processors)
|
1020
|
+
|
1021
|
+
def forward(
|
1022
|
+
self,
|
1023
|
+
sample: Tensor,
|
1024
|
+
timestep: Union[torch.Tensor, float, int],
|
1025
|
+
encoder_hidden_states: torch.Tensor,
|
1026
|
+
controlnet_cond: Optional[torch.Tensor] = None,
|
1027
|
+
conditioning_scale: Optional[float] = 1.0,
|
1028
|
+
class_labels: Optional[torch.Tensor] = None,
|
1029
|
+
timestep_cond: Optional[torch.Tensor] = None,
|
1030
|
+
attention_mask: Optional[torch.Tensor] = None,
|
1031
|
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
1032
|
+
added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
|
1033
|
+
return_dict: bool = True,
|
1034
|
+
apply_control: bool = True,
|
1035
|
+
) -> Union[ControlNetXSOutput, Tuple]:
|
1036
|
+
"""
|
1037
|
+
The [`ControlNetXSModel`] forward method.
|
1038
|
+
|
1039
|
+
Args:
|
1040
|
+
sample (`Tensor`):
|
1041
|
+
The noisy input tensor.
|
1042
|
+
timestep (`Union[torch.Tensor, float, int]`):
|
1043
|
+
The number of timesteps to denoise an input.
|
1044
|
+
encoder_hidden_states (`torch.Tensor`):
|
1045
|
+
The encoder hidden states.
|
1046
|
+
controlnet_cond (`Tensor`):
|
1047
|
+
The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
|
1048
|
+
conditioning_scale (`float`, defaults to `1.0`):
|
1049
|
+
How much the control model affects the base model outputs.
|
1050
|
+
class_labels (`torch.Tensor`, *optional*, defaults to `None`):
|
1051
|
+
Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
|
1052
|
+
timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
|
1053
|
+
Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
|
1054
|
+
timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
|
1055
|
+
embeddings.
|
1056
|
+
attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
|
1057
|
+
An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
|
1058
|
+
is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
|
1059
|
+
negative values to the attention scores corresponding to "discard" tokens.
|
1060
|
+
cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
|
1061
|
+
A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
|
1062
|
+
added_cond_kwargs (`dict`):
|
1063
|
+
Additional conditions for the Stable Diffusion XL UNet.
|
1064
|
+
return_dict (`bool`, defaults to `True`):
|
1065
|
+
Whether or not to return a [`~models.controlnets.controlnet.ControlNetOutput`] instead of a plain
|
1066
|
+
tuple.
|
1067
|
+
apply_control (`bool`, defaults to `True`):
|
1068
|
+
If `False`, the input is run only through the base model.
|
1069
|
+
|
1070
|
+
Returns:
|
1071
|
+
[`~models.controlnetxs.ControlNetXSOutput`] **or** `tuple`:
|
1072
|
+
If `return_dict` is `True`, a [`~models.controlnetxs.ControlNetXSOutput`] is returned, otherwise a
|
1073
|
+
tuple is returned where the first element is the sample tensor.
|
1074
|
+
"""
|
1075
|
+
|
1076
|
+
# check channel order
|
1077
|
+
if self.config.ctrl_conditioning_channel_order == "bgr":
|
1078
|
+
controlnet_cond = torch.flip(controlnet_cond, dims=[1])
|
1079
|
+
|
1080
|
+
# prepare attention_mask
|
1081
|
+
if attention_mask is not None:
|
1082
|
+
attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
|
1083
|
+
attention_mask = attention_mask.unsqueeze(1)
|
1084
|
+
|
1085
|
+
# 1. time
|
1086
|
+
timesteps = timestep
|
1087
|
+
if not torch.is_tensor(timesteps):
|
1088
|
+
# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
|
1089
|
+
# This would be a good case for the `match` statement (Python 3.10+)
|
1090
|
+
is_mps = sample.device.type == "mps"
|
1091
|
+
if isinstance(timestep, float):
|
1092
|
+
dtype = torch.float32 if is_mps else torch.float64
|
1093
|
+
else:
|
1094
|
+
dtype = torch.int32 if is_mps else torch.int64
|
1095
|
+
timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
|
1096
|
+
elif len(timesteps.shape) == 0:
|
1097
|
+
timesteps = timesteps[None].to(sample.device)
|
1098
|
+
|
1099
|
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
1100
|
+
timesteps = timesteps.expand(sample.shape[0])
|
1101
|
+
|
1102
|
+
t_emb = self.base_time_proj(timesteps)
|
1103
|
+
|
1104
|
+
# timesteps does not contain any weights and will always return f32 tensors
|
1105
|
+
# but time_embedding might actually be running in fp16. so we need to cast here.
|
1106
|
+
# there might be better ways to encapsulate this.
|
1107
|
+
t_emb = t_emb.to(dtype=sample.dtype)
|
1108
|
+
|
1109
|
+
if self.config.ctrl_learn_time_embedding and apply_control:
|
1110
|
+
ctrl_temb = self.ctrl_time_embedding(t_emb, timestep_cond)
|
1111
|
+
base_temb = self.base_time_embedding(t_emb, timestep_cond)
|
1112
|
+
interpolation_param = self.config.time_embedding_mix**0.3
|
1113
|
+
|
1114
|
+
temb = ctrl_temb * interpolation_param + base_temb * (1 - interpolation_param)
|
1115
|
+
else:
|
1116
|
+
temb = self.base_time_embedding(t_emb)
|
1117
|
+
|
1118
|
+
# added time & text embeddings
|
1119
|
+
aug_emb = None
|
1120
|
+
|
1121
|
+
if self.config.addition_embed_type is None:
|
1122
|
+
pass
|
1123
|
+
elif self.config.addition_embed_type == "text_time":
|
1124
|
+
# SDXL - style
|
1125
|
+
if "text_embeds" not in added_cond_kwargs:
|
1126
|
+
raise ValueError(
|
1127
|
+
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`"
|
1128
|
+
)
|
1129
|
+
text_embeds = added_cond_kwargs.get("text_embeds")
|
1130
|
+
if "time_ids" not in added_cond_kwargs:
|
1131
|
+
raise ValueError(
|
1132
|
+
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`"
|
1133
|
+
)
|
1134
|
+
time_ids = added_cond_kwargs.get("time_ids")
|
1135
|
+
time_embeds = self.base_add_time_proj(time_ids.flatten())
|
1136
|
+
time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
|
1137
|
+
add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
|
1138
|
+
add_embeds = add_embeds.to(temb.dtype)
|
1139
|
+
aug_emb = self.base_add_embedding(add_embeds)
|
1140
|
+
else:
|
1141
|
+
raise ValueError(
|
1142
|
+
f"ControlNet-XS currently only supports StableDiffusion and StableDiffusion-XL, so addition_embed_type = {self.config.addition_embed_type} is currently not supported."
|
1143
|
+
)
|
1144
|
+
|
1145
|
+
temb = temb + aug_emb if aug_emb is not None else temb
|
1146
|
+
|
1147
|
+
# text embeddings
|
1148
|
+
cemb = encoder_hidden_states
|
1149
|
+
|
1150
|
+
# Preparation
|
1151
|
+
h_ctrl = h_base = sample
|
1152
|
+
hs_base, hs_ctrl = [], []
|
1153
|
+
|
1154
|
+
# Cross Control
|
1155
|
+
guided_hint = self.controlnet_cond_embedding(controlnet_cond)
|
1156
|
+
|
1157
|
+
# 1 - conv in & down
|
1158
|
+
|
1159
|
+
h_base = self.base_conv_in(h_base)
|
1160
|
+
h_ctrl = self.ctrl_conv_in(h_ctrl)
|
1161
|
+
if guided_hint is not None:
|
1162
|
+
h_ctrl += guided_hint
|
1163
|
+
if apply_control:
|
1164
|
+
h_base = h_base + self.control_to_base_for_conv_in(h_ctrl) * conditioning_scale # add ctrl -> base
|
1165
|
+
|
1166
|
+
hs_base.append(h_base)
|
1167
|
+
hs_ctrl.append(h_ctrl)
|
1168
|
+
|
1169
|
+
for down in self.down_blocks:
|
1170
|
+
h_base, h_ctrl, residual_hb, residual_hc = down(
|
1171
|
+
hidden_states_base=h_base,
|
1172
|
+
hidden_states_ctrl=h_ctrl,
|
1173
|
+
temb=temb,
|
1174
|
+
encoder_hidden_states=cemb,
|
1175
|
+
conditioning_scale=conditioning_scale,
|
1176
|
+
cross_attention_kwargs=cross_attention_kwargs,
|
1177
|
+
attention_mask=attention_mask,
|
1178
|
+
apply_control=apply_control,
|
1179
|
+
)
|
1180
|
+
hs_base.extend(residual_hb)
|
1181
|
+
hs_ctrl.extend(residual_hc)
|
1182
|
+
|
1183
|
+
# 2 - mid
|
1184
|
+
h_base, h_ctrl = self.mid_block(
|
1185
|
+
hidden_states_base=h_base,
|
1186
|
+
hidden_states_ctrl=h_ctrl,
|
1187
|
+
temb=temb,
|
1188
|
+
encoder_hidden_states=cemb,
|
1189
|
+
conditioning_scale=conditioning_scale,
|
1190
|
+
cross_attention_kwargs=cross_attention_kwargs,
|
1191
|
+
attention_mask=attention_mask,
|
1192
|
+
apply_control=apply_control,
|
1193
|
+
)
|
1194
|
+
|
1195
|
+
# 3 - up
|
1196
|
+
for up in self.up_blocks:
|
1197
|
+
n_resnets = len(up.resnets)
|
1198
|
+
skips_hb = hs_base[-n_resnets:]
|
1199
|
+
skips_hc = hs_ctrl[-n_resnets:]
|
1200
|
+
hs_base = hs_base[:-n_resnets]
|
1201
|
+
hs_ctrl = hs_ctrl[:-n_resnets]
|
1202
|
+
h_base = up(
|
1203
|
+
hidden_states=h_base,
|
1204
|
+
res_hidden_states_tuple_base=skips_hb,
|
1205
|
+
res_hidden_states_tuple_ctrl=skips_hc,
|
1206
|
+
temb=temb,
|
1207
|
+
encoder_hidden_states=cemb,
|
1208
|
+
conditioning_scale=conditioning_scale,
|
1209
|
+
cross_attention_kwargs=cross_attention_kwargs,
|
1210
|
+
attention_mask=attention_mask,
|
1211
|
+
apply_control=apply_control,
|
1212
|
+
)
|
1213
|
+
|
1214
|
+
# 4 - conv out
|
1215
|
+
h_base = self.base_conv_norm_out(h_base)
|
1216
|
+
h_base = self.base_conv_act(h_base)
|
1217
|
+
h_base = self.base_conv_out(h_base)
|
1218
|
+
|
1219
|
+
if not return_dict:
|
1220
|
+
return (h_base,)
|
1221
|
+
|
1222
|
+
return ControlNetXSOutput(sample=h_base)
|
1223
|
+
|
1224
|
+
|
1225
|
+
class ControlNetXSCrossAttnDownBlock2D(nn.Module):
|
1226
|
+
def __init__(
|
1227
|
+
self,
|
1228
|
+
base_in_channels: int,
|
1229
|
+
base_out_channels: int,
|
1230
|
+
ctrl_in_channels: int,
|
1231
|
+
ctrl_out_channels: int,
|
1232
|
+
temb_channels: int,
|
1233
|
+
norm_num_groups: int = 32,
|
1234
|
+
ctrl_max_norm_num_groups: int = 32,
|
1235
|
+
has_crossattn=True,
|
1236
|
+
transformer_layers_per_block: Optional[Union[int, Tuple[int]]] = 1,
|
1237
|
+
base_num_attention_heads: Optional[int] = 1,
|
1238
|
+
ctrl_num_attention_heads: Optional[int] = 1,
|
1239
|
+
cross_attention_dim: Optional[int] = 1024,
|
1240
|
+
add_downsample: bool = True,
|
1241
|
+
upcast_attention: Optional[bool] = False,
|
1242
|
+
use_linear_projection: Optional[bool] = True,
|
1243
|
+
):
|
1244
|
+
super().__init__()
|
1245
|
+
base_resnets = []
|
1246
|
+
base_attentions = []
|
1247
|
+
ctrl_resnets = []
|
1248
|
+
ctrl_attentions = []
|
1249
|
+
ctrl_to_base = []
|
1250
|
+
base_to_ctrl = []
|
1251
|
+
|
1252
|
+
num_layers = 2 # only support sd + sdxl
|
1253
|
+
|
1254
|
+
if isinstance(transformer_layers_per_block, int):
|
1255
|
+
transformer_layers_per_block = [transformer_layers_per_block] * num_layers
|
1256
|
+
|
1257
|
+
for i in range(num_layers):
|
1258
|
+
base_in_channels = base_in_channels if i == 0 else base_out_channels
|
1259
|
+
ctrl_in_channels = ctrl_in_channels if i == 0 else ctrl_out_channels
|
1260
|
+
|
1261
|
+
# Before the resnet/attention application, information is concatted from base to control.
|
1262
|
+
# Concat doesn't require change in number of channels
|
1263
|
+
base_to_ctrl.append(make_zero_conv(base_in_channels, base_in_channels))
|
1264
|
+
|
1265
|
+
base_resnets.append(
|
1266
|
+
ResnetBlock2D(
|
1267
|
+
in_channels=base_in_channels,
|
1268
|
+
out_channels=base_out_channels,
|
1269
|
+
temb_channels=temb_channels,
|
1270
|
+
groups=norm_num_groups,
|
1271
|
+
)
|
1272
|
+
)
|
1273
|
+
ctrl_resnets.append(
|
1274
|
+
ResnetBlock2D(
|
1275
|
+
in_channels=ctrl_in_channels + base_in_channels, # information from base is concatted to ctrl
|
1276
|
+
out_channels=ctrl_out_channels,
|
1277
|
+
temb_channels=temb_channels,
|
1278
|
+
groups=find_largest_factor(
|
1279
|
+
ctrl_in_channels + base_in_channels, max_factor=ctrl_max_norm_num_groups
|
1280
|
+
),
|
1281
|
+
groups_out=find_largest_factor(ctrl_out_channels, max_factor=ctrl_max_norm_num_groups),
|
1282
|
+
eps=1e-5,
|
1283
|
+
)
|
1284
|
+
)
|
1285
|
+
|
1286
|
+
if has_crossattn:
|
1287
|
+
base_attentions.append(
|
1288
|
+
Transformer2DModel(
|
1289
|
+
base_num_attention_heads,
|
1290
|
+
base_out_channels // base_num_attention_heads,
|
1291
|
+
in_channels=base_out_channels,
|
1292
|
+
num_layers=transformer_layers_per_block[i],
|
1293
|
+
cross_attention_dim=cross_attention_dim,
|
1294
|
+
use_linear_projection=use_linear_projection,
|
1295
|
+
upcast_attention=upcast_attention,
|
1296
|
+
norm_num_groups=norm_num_groups,
|
1297
|
+
)
|
1298
|
+
)
|
1299
|
+
ctrl_attentions.append(
|
1300
|
+
Transformer2DModel(
|
1301
|
+
ctrl_num_attention_heads,
|
1302
|
+
ctrl_out_channels // ctrl_num_attention_heads,
|
1303
|
+
in_channels=ctrl_out_channels,
|
1304
|
+
num_layers=transformer_layers_per_block[i],
|
1305
|
+
cross_attention_dim=cross_attention_dim,
|
1306
|
+
use_linear_projection=use_linear_projection,
|
1307
|
+
upcast_attention=upcast_attention,
|
1308
|
+
norm_num_groups=find_largest_factor(ctrl_out_channels, max_factor=ctrl_max_norm_num_groups),
|
1309
|
+
)
|
1310
|
+
)
|
1311
|
+
|
1312
|
+
# After the resnet/attention application, information is added from control to base
|
1313
|
+
# Addition requires change in number of channels
|
1314
|
+
ctrl_to_base.append(make_zero_conv(ctrl_out_channels, base_out_channels))
|
1315
|
+
|
1316
|
+
if add_downsample:
|
1317
|
+
# Before the downsampler application, information is concatted from base to control
|
1318
|
+
# Concat doesn't require change in number of channels
|
1319
|
+
base_to_ctrl.append(make_zero_conv(base_out_channels, base_out_channels))
|
1320
|
+
|
1321
|
+
self.base_downsamplers = Downsample2D(
|
1322
|
+
base_out_channels, use_conv=True, out_channels=base_out_channels, name="op"
|
1323
|
+
)
|
1324
|
+
self.ctrl_downsamplers = Downsample2D(
|
1325
|
+
ctrl_out_channels + base_out_channels, use_conv=True, out_channels=ctrl_out_channels, name="op"
|
1326
|
+
)
|
1327
|
+
|
1328
|
+
# After the downsampler application, information is added from control to base
|
1329
|
+
# Addition requires change in number of channels
|
1330
|
+
ctrl_to_base.append(make_zero_conv(ctrl_out_channels, base_out_channels))
|
1331
|
+
else:
|
1332
|
+
self.base_downsamplers = None
|
1333
|
+
self.ctrl_downsamplers = None
|
1334
|
+
|
1335
|
+
self.base_resnets = nn.ModuleList(base_resnets)
|
1336
|
+
self.ctrl_resnets = nn.ModuleList(ctrl_resnets)
|
1337
|
+
self.base_attentions = nn.ModuleList(base_attentions) if has_crossattn else [None] * num_layers
|
1338
|
+
self.ctrl_attentions = nn.ModuleList(ctrl_attentions) if has_crossattn else [None] * num_layers
|
1339
|
+
self.base_to_ctrl = nn.ModuleList(base_to_ctrl)
|
1340
|
+
self.ctrl_to_base = nn.ModuleList(ctrl_to_base)
|
1341
|
+
|
1342
|
+
self.gradient_checkpointing = False
|
1343
|
+
|
1344
|
+
@classmethod
|
1345
|
+
def from_modules(cls, base_downblock: CrossAttnDownBlock2D, ctrl_downblock: DownBlockControlNetXSAdapter):
|
1346
|
+
# get params
|
1347
|
+
def get_first_cross_attention(block):
|
1348
|
+
return block.attentions[0].transformer_blocks[0].attn2
|
1349
|
+
|
1350
|
+
base_in_channels = base_downblock.resnets[0].in_channels
|
1351
|
+
base_out_channels = base_downblock.resnets[0].out_channels
|
1352
|
+
ctrl_in_channels = (
|
1353
|
+
ctrl_downblock.resnets[0].in_channels - base_in_channels
|
1354
|
+
) # base channels are concatted to ctrl channels in init
|
1355
|
+
ctrl_out_channels = ctrl_downblock.resnets[0].out_channels
|
1356
|
+
temb_channels = base_downblock.resnets[0].time_emb_proj.in_features
|
1357
|
+
num_groups = base_downblock.resnets[0].norm1.num_groups
|
1358
|
+
ctrl_num_groups = ctrl_downblock.resnets[0].norm1.num_groups
|
1359
|
+
if hasattr(base_downblock, "attentions"):
|
1360
|
+
has_crossattn = True
|
1361
|
+
transformer_layers_per_block = len(base_downblock.attentions[0].transformer_blocks)
|
1362
|
+
base_num_attention_heads = get_first_cross_attention(base_downblock).heads
|
1363
|
+
ctrl_num_attention_heads = get_first_cross_attention(ctrl_downblock).heads
|
1364
|
+
cross_attention_dim = get_first_cross_attention(base_downblock).cross_attention_dim
|
1365
|
+
upcast_attention = get_first_cross_attention(base_downblock).upcast_attention
|
1366
|
+
use_linear_projection = base_downblock.attentions[0].use_linear_projection
|
1367
|
+
else:
|
1368
|
+
has_crossattn = False
|
1369
|
+
transformer_layers_per_block = None
|
1370
|
+
base_num_attention_heads = None
|
1371
|
+
ctrl_num_attention_heads = None
|
1372
|
+
cross_attention_dim = None
|
1373
|
+
upcast_attention = None
|
1374
|
+
use_linear_projection = None
|
1375
|
+
add_downsample = base_downblock.downsamplers is not None
|
1376
|
+
|
1377
|
+
# create model
|
1378
|
+
model = cls(
|
1379
|
+
base_in_channels=base_in_channels,
|
1380
|
+
base_out_channels=base_out_channels,
|
1381
|
+
ctrl_in_channels=ctrl_in_channels,
|
1382
|
+
ctrl_out_channels=ctrl_out_channels,
|
1383
|
+
temb_channels=temb_channels,
|
1384
|
+
norm_num_groups=num_groups,
|
1385
|
+
ctrl_max_norm_num_groups=ctrl_num_groups,
|
1386
|
+
has_crossattn=has_crossattn,
|
1387
|
+
transformer_layers_per_block=transformer_layers_per_block,
|
1388
|
+
base_num_attention_heads=base_num_attention_heads,
|
1389
|
+
ctrl_num_attention_heads=ctrl_num_attention_heads,
|
1390
|
+
cross_attention_dim=cross_attention_dim,
|
1391
|
+
add_downsample=add_downsample,
|
1392
|
+
upcast_attention=upcast_attention,
|
1393
|
+
use_linear_projection=use_linear_projection,
|
1394
|
+
)
|
1395
|
+
|
1396
|
+
# # load weights
|
1397
|
+
model.base_resnets.load_state_dict(base_downblock.resnets.state_dict())
|
1398
|
+
model.ctrl_resnets.load_state_dict(ctrl_downblock.resnets.state_dict())
|
1399
|
+
if has_crossattn:
|
1400
|
+
model.base_attentions.load_state_dict(base_downblock.attentions.state_dict())
|
1401
|
+
model.ctrl_attentions.load_state_dict(ctrl_downblock.attentions.state_dict())
|
1402
|
+
if add_downsample:
|
1403
|
+
model.base_downsamplers.load_state_dict(base_downblock.downsamplers[0].state_dict())
|
1404
|
+
model.ctrl_downsamplers.load_state_dict(ctrl_downblock.downsamplers.state_dict())
|
1405
|
+
model.base_to_ctrl.load_state_dict(ctrl_downblock.base_to_ctrl.state_dict())
|
1406
|
+
model.ctrl_to_base.load_state_dict(ctrl_downblock.ctrl_to_base.state_dict())
|
1407
|
+
|
1408
|
+
return model
|
1409
|
+
|
1410
|
+
def freeze_base_params(self) -> None:
|
1411
|
+
"""Freeze the weights of the parts belonging to the base UNet2DConditionModel, and leave everything else unfrozen for fine
|
1412
|
+
tuning."""
|
1413
|
+
# Unfreeze everything
|
1414
|
+
for param in self.parameters():
|
1415
|
+
param.requires_grad = True
|
1416
|
+
|
1417
|
+
# Freeze base part
|
1418
|
+
base_parts = [self.base_resnets]
|
1419
|
+
if isinstance(self.base_attentions, nn.ModuleList): # attentions can be a list of Nones
|
1420
|
+
base_parts.append(self.base_attentions)
|
1421
|
+
if self.base_downsamplers is not None:
|
1422
|
+
base_parts.append(self.base_downsamplers)
|
1423
|
+
for part in base_parts:
|
1424
|
+
for param in part.parameters():
|
1425
|
+
param.requires_grad = False
|
1426
|
+
|
1427
|
+
def forward(
|
1428
|
+
self,
|
1429
|
+
hidden_states_base: Tensor,
|
1430
|
+
temb: Tensor,
|
1431
|
+
encoder_hidden_states: Optional[Tensor] = None,
|
1432
|
+
hidden_states_ctrl: Optional[Tensor] = None,
|
1433
|
+
conditioning_scale: Optional[float] = 1.0,
|
1434
|
+
attention_mask: Optional[Tensor] = None,
|
1435
|
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
1436
|
+
encoder_attention_mask: Optional[Tensor] = None,
|
1437
|
+
apply_control: bool = True,
|
1438
|
+
) -> Tuple[Tensor, Tensor, Tuple[Tensor, ...], Tuple[Tensor, ...]]:
|
1439
|
+
if cross_attention_kwargs is not None:
|
1440
|
+
if cross_attention_kwargs.get("scale", None) is not None:
|
1441
|
+
logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
|
1442
|
+
|
1443
|
+
h_base = hidden_states_base
|
1444
|
+
h_ctrl = hidden_states_ctrl
|
1445
|
+
|
1446
|
+
base_output_states = ()
|
1447
|
+
ctrl_output_states = ()
|
1448
|
+
|
1449
|
+
base_blocks = list(zip(self.base_resnets, self.base_attentions))
|
1450
|
+
ctrl_blocks = list(zip(self.ctrl_resnets, self.ctrl_attentions))
|
1451
|
+
|
1452
|
+
def create_custom_forward(module, return_dict=None):
|
1453
|
+
def custom_forward(*inputs):
|
1454
|
+
if return_dict is not None:
|
1455
|
+
return module(*inputs, return_dict=return_dict)
|
1456
|
+
else:
|
1457
|
+
return module(*inputs)
|
1458
|
+
|
1459
|
+
return custom_forward
|
1460
|
+
|
1461
|
+
for (b_res, b_attn), (c_res, c_attn), b2c, c2b in zip(
|
1462
|
+
base_blocks, ctrl_blocks, self.base_to_ctrl, self.ctrl_to_base
|
1463
|
+
):
|
1464
|
+
# concat base -> ctrl
|
1465
|
+
if apply_control:
|
1466
|
+
h_ctrl = torch.cat([h_ctrl, b2c(h_base)], dim=1)
|
1467
|
+
|
1468
|
+
# apply base subblock
|
1469
|
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
1470
|
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
1471
|
+
h_base = torch.utils.checkpoint.checkpoint(
|
1472
|
+
create_custom_forward(b_res),
|
1473
|
+
h_base,
|
1474
|
+
temb,
|
1475
|
+
**ckpt_kwargs,
|
1476
|
+
)
|
1477
|
+
else:
|
1478
|
+
h_base = b_res(h_base, temb)
|
1479
|
+
|
1480
|
+
if b_attn is not None:
|
1481
|
+
h_base = b_attn(
|
1482
|
+
h_base,
|
1483
|
+
encoder_hidden_states=encoder_hidden_states,
|
1484
|
+
cross_attention_kwargs=cross_attention_kwargs,
|
1485
|
+
attention_mask=attention_mask,
|
1486
|
+
encoder_attention_mask=encoder_attention_mask,
|
1487
|
+
return_dict=False,
|
1488
|
+
)[0]
|
1489
|
+
|
1490
|
+
# apply ctrl subblock
|
1491
|
+
if apply_control:
|
1492
|
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
1493
|
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
1494
|
+
h_ctrl = torch.utils.checkpoint.checkpoint(
|
1495
|
+
create_custom_forward(c_res),
|
1496
|
+
h_ctrl,
|
1497
|
+
temb,
|
1498
|
+
**ckpt_kwargs,
|
1499
|
+
)
|
1500
|
+
else:
|
1501
|
+
h_ctrl = c_res(h_ctrl, temb)
|
1502
|
+
if c_attn is not None:
|
1503
|
+
h_ctrl = c_attn(
|
1504
|
+
h_ctrl,
|
1505
|
+
encoder_hidden_states=encoder_hidden_states,
|
1506
|
+
cross_attention_kwargs=cross_attention_kwargs,
|
1507
|
+
attention_mask=attention_mask,
|
1508
|
+
encoder_attention_mask=encoder_attention_mask,
|
1509
|
+
return_dict=False,
|
1510
|
+
)[0]
|
1511
|
+
|
1512
|
+
# add ctrl -> base
|
1513
|
+
if apply_control:
|
1514
|
+
h_base = h_base + c2b(h_ctrl) * conditioning_scale
|
1515
|
+
|
1516
|
+
base_output_states = base_output_states + (h_base,)
|
1517
|
+
ctrl_output_states = ctrl_output_states + (h_ctrl,)
|
1518
|
+
|
1519
|
+
if self.base_downsamplers is not None: # if we have a base_downsampler, then also a ctrl_downsampler
|
1520
|
+
b2c = self.base_to_ctrl[-1]
|
1521
|
+
c2b = self.ctrl_to_base[-1]
|
1522
|
+
|
1523
|
+
# concat base -> ctrl
|
1524
|
+
if apply_control:
|
1525
|
+
h_ctrl = torch.cat([h_ctrl, b2c(h_base)], dim=1)
|
1526
|
+
# apply base subblock
|
1527
|
+
h_base = self.base_downsamplers(h_base)
|
1528
|
+
# apply ctrl subblock
|
1529
|
+
if apply_control:
|
1530
|
+
h_ctrl = self.ctrl_downsamplers(h_ctrl)
|
1531
|
+
# add ctrl -> base
|
1532
|
+
if apply_control:
|
1533
|
+
h_base = h_base + c2b(h_ctrl) * conditioning_scale
|
1534
|
+
|
1535
|
+
base_output_states = base_output_states + (h_base,)
|
1536
|
+
ctrl_output_states = ctrl_output_states + (h_ctrl,)
|
1537
|
+
|
1538
|
+
return h_base, h_ctrl, base_output_states, ctrl_output_states
|
1539
|
+
|
1540
|
+
|
1541
|
+
class ControlNetXSCrossAttnMidBlock2D(nn.Module):
|
1542
|
+
def __init__(
|
1543
|
+
self,
|
1544
|
+
base_channels: int,
|
1545
|
+
ctrl_channels: int,
|
1546
|
+
temb_channels: Optional[int] = None,
|
1547
|
+
norm_num_groups: int = 32,
|
1548
|
+
ctrl_max_norm_num_groups: int = 32,
|
1549
|
+
transformer_layers_per_block: int = 1,
|
1550
|
+
base_num_attention_heads: Optional[int] = 1,
|
1551
|
+
ctrl_num_attention_heads: Optional[int] = 1,
|
1552
|
+
cross_attention_dim: Optional[int] = 1024,
|
1553
|
+
upcast_attention: bool = False,
|
1554
|
+
use_linear_projection: Optional[bool] = True,
|
1555
|
+
):
|
1556
|
+
super().__init__()
|
1557
|
+
|
1558
|
+
# Before the midblock application, information is concatted from base to control.
|
1559
|
+
# Concat doesn't require change in number of channels
|
1560
|
+
self.base_to_ctrl = make_zero_conv(base_channels, base_channels)
|
1561
|
+
|
1562
|
+
self.base_midblock = UNetMidBlock2DCrossAttn(
|
1563
|
+
transformer_layers_per_block=transformer_layers_per_block,
|
1564
|
+
in_channels=base_channels,
|
1565
|
+
temb_channels=temb_channels,
|
1566
|
+
resnet_groups=norm_num_groups,
|
1567
|
+
cross_attention_dim=cross_attention_dim,
|
1568
|
+
num_attention_heads=base_num_attention_heads,
|
1569
|
+
use_linear_projection=use_linear_projection,
|
1570
|
+
upcast_attention=upcast_attention,
|
1571
|
+
)
|
1572
|
+
|
1573
|
+
self.ctrl_midblock = UNetMidBlock2DCrossAttn(
|
1574
|
+
transformer_layers_per_block=transformer_layers_per_block,
|
1575
|
+
in_channels=ctrl_channels + base_channels,
|
1576
|
+
out_channels=ctrl_channels,
|
1577
|
+
temb_channels=temb_channels,
|
1578
|
+
# number or norm groups must divide both in_channels and out_channels
|
1579
|
+
resnet_groups=find_largest_factor(
|
1580
|
+
gcd(ctrl_channels, ctrl_channels + base_channels), ctrl_max_norm_num_groups
|
1581
|
+
),
|
1582
|
+
cross_attention_dim=cross_attention_dim,
|
1583
|
+
num_attention_heads=ctrl_num_attention_heads,
|
1584
|
+
use_linear_projection=use_linear_projection,
|
1585
|
+
upcast_attention=upcast_attention,
|
1586
|
+
)
|
1587
|
+
|
1588
|
+
# After the midblock application, information is added from control to base
|
1589
|
+
# Addition requires change in number of channels
|
1590
|
+
self.ctrl_to_base = make_zero_conv(ctrl_channels, base_channels)
|
1591
|
+
|
1592
|
+
self.gradient_checkpointing = False
|
1593
|
+
|
1594
|
+
@classmethod
|
1595
|
+
def from_modules(
|
1596
|
+
cls,
|
1597
|
+
base_midblock: UNetMidBlock2DCrossAttn,
|
1598
|
+
ctrl_midblock: MidBlockControlNetXSAdapter,
|
1599
|
+
):
|
1600
|
+
base_to_ctrl = ctrl_midblock.base_to_ctrl
|
1601
|
+
ctrl_to_base = ctrl_midblock.ctrl_to_base
|
1602
|
+
ctrl_midblock = ctrl_midblock.midblock
|
1603
|
+
|
1604
|
+
# get params
|
1605
|
+
def get_first_cross_attention(midblock):
|
1606
|
+
return midblock.attentions[0].transformer_blocks[0].attn2
|
1607
|
+
|
1608
|
+
base_channels = ctrl_to_base.out_channels
|
1609
|
+
ctrl_channels = ctrl_to_base.in_channels
|
1610
|
+
transformer_layers_per_block = len(base_midblock.attentions[0].transformer_blocks)
|
1611
|
+
temb_channels = base_midblock.resnets[0].time_emb_proj.in_features
|
1612
|
+
num_groups = base_midblock.resnets[0].norm1.num_groups
|
1613
|
+
ctrl_num_groups = ctrl_midblock.resnets[0].norm1.num_groups
|
1614
|
+
base_num_attention_heads = get_first_cross_attention(base_midblock).heads
|
1615
|
+
ctrl_num_attention_heads = get_first_cross_attention(ctrl_midblock).heads
|
1616
|
+
cross_attention_dim = get_first_cross_attention(base_midblock).cross_attention_dim
|
1617
|
+
upcast_attention = get_first_cross_attention(base_midblock).upcast_attention
|
1618
|
+
use_linear_projection = base_midblock.attentions[0].use_linear_projection
|
1619
|
+
|
1620
|
+
# create model
|
1621
|
+
model = cls(
|
1622
|
+
base_channels=base_channels,
|
1623
|
+
ctrl_channels=ctrl_channels,
|
1624
|
+
temb_channels=temb_channels,
|
1625
|
+
norm_num_groups=num_groups,
|
1626
|
+
ctrl_max_norm_num_groups=ctrl_num_groups,
|
1627
|
+
transformer_layers_per_block=transformer_layers_per_block,
|
1628
|
+
base_num_attention_heads=base_num_attention_heads,
|
1629
|
+
ctrl_num_attention_heads=ctrl_num_attention_heads,
|
1630
|
+
cross_attention_dim=cross_attention_dim,
|
1631
|
+
upcast_attention=upcast_attention,
|
1632
|
+
use_linear_projection=use_linear_projection,
|
1633
|
+
)
|
1634
|
+
|
1635
|
+
# load weights
|
1636
|
+
model.base_to_ctrl.load_state_dict(base_to_ctrl.state_dict())
|
1637
|
+
model.base_midblock.load_state_dict(base_midblock.state_dict())
|
1638
|
+
model.ctrl_midblock.load_state_dict(ctrl_midblock.state_dict())
|
1639
|
+
model.ctrl_to_base.load_state_dict(ctrl_to_base.state_dict())
|
1640
|
+
|
1641
|
+
return model
|
1642
|
+
|
1643
|
+
def freeze_base_params(self) -> None:
|
1644
|
+
"""Freeze the weights of the parts belonging to the base UNet2DConditionModel, and leave everything else unfrozen for fine
|
1645
|
+
tuning."""
|
1646
|
+
# Unfreeze everything
|
1647
|
+
for param in self.parameters():
|
1648
|
+
param.requires_grad = True
|
1649
|
+
|
1650
|
+
# Freeze base part
|
1651
|
+
for param in self.base_midblock.parameters():
|
1652
|
+
param.requires_grad = False
|
1653
|
+
|
1654
|
+
def forward(
|
1655
|
+
self,
|
1656
|
+
hidden_states_base: Tensor,
|
1657
|
+
temb: Tensor,
|
1658
|
+
encoder_hidden_states: Tensor,
|
1659
|
+
hidden_states_ctrl: Optional[Tensor] = None,
|
1660
|
+
conditioning_scale: Optional[float] = 1.0,
|
1661
|
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
1662
|
+
attention_mask: Optional[Tensor] = None,
|
1663
|
+
encoder_attention_mask: Optional[Tensor] = None,
|
1664
|
+
apply_control: bool = True,
|
1665
|
+
) -> Tuple[Tensor, Tensor]:
|
1666
|
+
if cross_attention_kwargs is not None:
|
1667
|
+
if cross_attention_kwargs.get("scale", None) is not None:
|
1668
|
+
logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
|
1669
|
+
|
1670
|
+
h_base = hidden_states_base
|
1671
|
+
h_ctrl = hidden_states_ctrl
|
1672
|
+
|
1673
|
+
joint_args = {
|
1674
|
+
"temb": temb,
|
1675
|
+
"encoder_hidden_states": encoder_hidden_states,
|
1676
|
+
"attention_mask": attention_mask,
|
1677
|
+
"cross_attention_kwargs": cross_attention_kwargs,
|
1678
|
+
"encoder_attention_mask": encoder_attention_mask,
|
1679
|
+
}
|
1680
|
+
|
1681
|
+
if apply_control:
|
1682
|
+
h_ctrl = torch.cat([h_ctrl, self.base_to_ctrl(h_base)], dim=1) # concat base -> ctrl
|
1683
|
+
h_base = self.base_midblock(h_base, **joint_args) # apply base mid block
|
1684
|
+
if apply_control:
|
1685
|
+
h_ctrl = self.ctrl_midblock(h_ctrl, **joint_args) # apply ctrl mid block
|
1686
|
+
h_base = h_base + self.ctrl_to_base(h_ctrl) * conditioning_scale # add ctrl -> base
|
1687
|
+
|
1688
|
+
return h_base, h_ctrl
|
1689
|
+
|
1690
|
+
|
1691
|
+
class ControlNetXSCrossAttnUpBlock2D(nn.Module):
|
1692
|
+
def __init__(
|
1693
|
+
self,
|
1694
|
+
in_channels: int,
|
1695
|
+
out_channels: int,
|
1696
|
+
prev_output_channel: int,
|
1697
|
+
ctrl_skip_channels: List[int],
|
1698
|
+
temb_channels: int,
|
1699
|
+
norm_num_groups: int = 32,
|
1700
|
+
resolution_idx: Optional[int] = None,
|
1701
|
+
has_crossattn=True,
|
1702
|
+
transformer_layers_per_block: int = 1,
|
1703
|
+
num_attention_heads: int = 1,
|
1704
|
+
cross_attention_dim: int = 1024,
|
1705
|
+
add_upsample: bool = True,
|
1706
|
+
upcast_attention: bool = False,
|
1707
|
+
use_linear_projection: Optional[bool] = True,
|
1708
|
+
):
|
1709
|
+
super().__init__()
|
1710
|
+
resnets = []
|
1711
|
+
attentions = []
|
1712
|
+
ctrl_to_base = []
|
1713
|
+
|
1714
|
+
num_layers = 3 # only support sd + sdxl
|
1715
|
+
|
1716
|
+
self.has_cross_attention = has_crossattn
|
1717
|
+
self.num_attention_heads = num_attention_heads
|
1718
|
+
|
1719
|
+
if isinstance(transformer_layers_per_block, int):
|
1720
|
+
transformer_layers_per_block = [transformer_layers_per_block] * num_layers
|
1721
|
+
|
1722
|
+
for i in range(num_layers):
|
1723
|
+
res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
|
1724
|
+
resnet_in_channels = prev_output_channel if i == 0 else out_channels
|
1725
|
+
|
1726
|
+
ctrl_to_base.append(make_zero_conv(ctrl_skip_channels[i], resnet_in_channels))
|
1727
|
+
|
1728
|
+
resnets.append(
|
1729
|
+
ResnetBlock2D(
|
1730
|
+
in_channels=resnet_in_channels + res_skip_channels,
|
1731
|
+
out_channels=out_channels,
|
1732
|
+
temb_channels=temb_channels,
|
1733
|
+
groups=norm_num_groups,
|
1734
|
+
)
|
1735
|
+
)
|
1736
|
+
|
1737
|
+
if has_crossattn:
|
1738
|
+
attentions.append(
|
1739
|
+
Transformer2DModel(
|
1740
|
+
num_attention_heads,
|
1741
|
+
out_channels // num_attention_heads,
|
1742
|
+
in_channels=out_channels,
|
1743
|
+
num_layers=transformer_layers_per_block[i],
|
1744
|
+
cross_attention_dim=cross_attention_dim,
|
1745
|
+
use_linear_projection=use_linear_projection,
|
1746
|
+
upcast_attention=upcast_attention,
|
1747
|
+
norm_num_groups=norm_num_groups,
|
1748
|
+
)
|
1749
|
+
)
|
1750
|
+
|
1751
|
+
self.resnets = nn.ModuleList(resnets)
|
1752
|
+
self.attentions = nn.ModuleList(attentions) if has_crossattn else [None] * num_layers
|
1753
|
+
self.ctrl_to_base = nn.ModuleList(ctrl_to_base)
|
1754
|
+
|
1755
|
+
if add_upsample:
|
1756
|
+
self.upsamplers = Upsample2D(out_channels, use_conv=True, out_channels=out_channels)
|
1757
|
+
else:
|
1758
|
+
self.upsamplers = None
|
1759
|
+
|
1760
|
+
self.gradient_checkpointing = False
|
1761
|
+
self.resolution_idx = resolution_idx
|
1762
|
+
|
1763
|
+
@classmethod
|
1764
|
+
def from_modules(cls, base_upblock: CrossAttnUpBlock2D, ctrl_upblock: UpBlockControlNetXSAdapter):
|
1765
|
+
ctrl_to_base_skip_connections = ctrl_upblock.ctrl_to_base
|
1766
|
+
|
1767
|
+
# get params
|
1768
|
+
def get_first_cross_attention(block):
|
1769
|
+
return block.attentions[0].transformer_blocks[0].attn2
|
1770
|
+
|
1771
|
+
out_channels = base_upblock.resnets[0].out_channels
|
1772
|
+
in_channels = base_upblock.resnets[-1].in_channels - out_channels
|
1773
|
+
prev_output_channels = base_upblock.resnets[0].in_channels - out_channels
|
1774
|
+
ctrl_skip_channelss = [c.in_channels for c in ctrl_to_base_skip_connections]
|
1775
|
+
temb_channels = base_upblock.resnets[0].time_emb_proj.in_features
|
1776
|
+
num_groups = base_upblock.resnets[0].norm1.num_groups
|
1777
|
+
resolution_idx = base_upblock.resolution_idx
|
1778
|
+
if hasattr(base_upblock, "attentions"):
|
1779
|
+
has_crossattn = True
|
1780
|
+
transformer_layers_per_block = len(base_upblock.attentions[0].transformer_blocks)
|
1781
|
+
num_attention_heads = get_first_cross_attention(base_upblock).heads
|
1782
|
+
cross_attention_dim = get_first_cross_attention(base_upblock).cross_attention_dim
|
1783
|
+
upcast_attention = get_first_cross_attention(base_upblock).upcast_attention
|
1784
|
+
use_linear_projection = base_upblock.attentions[0].use_linear_projection
|
1785
|
+
else:
|
1786
|
+
has_crossattn = False
|
1787
|
+
transformer_layers_per_block = None
|
1788
|
+
num_attention_heads = None
|
1789
|
+
cross_attention_dim = None
|
1790
|
+
upcast_attention = None
|
1791
|
+
use_linear_projection = None
|
1792
|
+
add_upsample = base_upblock.upsamplers is not None
|
1793
|
+
|
1794
|
+
# create model
|
1795
|
+
model = cls(
|
1796
|
+
in_channels=in_channels,
|
1797
|
+
out_channels=out_channels,
|
1798
|
+
prev_output_channel=prev_output_channels,
|
1799
|
+
ctrl_skip_channels=ctrl_skip_channelss,
|
1800
|
+
temb_channels=temb_channels,
|
1801
|
+
norm_num_groups=num_groups,
|
1802
|
+
resolution_idx=resolution_idx,
|
1803
|
+
has_crossattn=has_crossattn,
|
1804
|
+
transformer_layers_per_block=transformer_layers_per_block,
|
1805
|
+
num_attention_heads=num_attention_heads,
|
1806
|
+
cross_attention_dim=cross_attention_dim,
|
1807
|
+
add_upsample=add_upsample,
|
1808
|
+
upcast_attention=upcast_attention,
|
1809
|
+
use_linear_projection=use_linear_projection,
|
1810
|
+
)
|
1811
|
+
|
1812
|
+
# load weights
|
1813
|
+
model.resnets.load_state_dict(base_upblock.resnets.state_dict())
|
1814
|
+
if has_crossattn:
|
1815
|
+
model.attentions.load_state_dict(base_upblock.attentions.state_dict())
|
1816
|
+
if add_upsample:
|
1817
|
+
model.upsamplers.load_state_dict(base_upblock.upsamplers[0].state_dict())
|
1818
|
+
model.ctrl_to_base.load_state_dict(ctrl_to_base_skip_connections.state_dict())
|
1819
|
+
|
1820
|
+
return model
|
1821
|
+
|
1822
|
+
def freeze_base_params(self) -> None:
|
1823
|
+
"""Freeze the weights of the parts belonging to the base UNet2DConditionModel, and leave everything else unfrozen for fine
|
1824
|
+
tuning."""
|
1825
|
+
# Unfreeze everything
|
1826
|
+
for param in self.parameters():
|
1827
|
+
param.requires_grad = True
|
1828
|
+
|
1829
|
+
# Freeze base part
|
1830
|
+
base_parts = [self.resnets]
|
1831
|
+
if isinstance(self.attentions, nn.ModuleList): # attentions can be a list of Nones
|
1832
|
+
base_parts.append(self.attentions)
|
1833
|
+
if self.upsamplers is not None:
|
1834
|
+
base_parts.append(self.upsamplers)
|
1835
|
+
for part in base_parts:
|
1836
|
+
for param in part.parameters():
|
1837
|
+
param.requires_grad = False
|
1838
|
+
|
1839
|
+
def forward(
|
1840
|
+
self,
|
1841
|
+
hidden_states: Tensor,
|
1842
|
+
res_hidden_states_tuple_base: Tuple[Tensor, ...],
|
1843
|
+
res_hidden_states_tuple_ctrl: Tuple[Tensor, ...],
|
1844
|
+
temb: Tensor,
|
1845
|
+
encoder_hidden_states: Optional[Tensor] = None,
|
1846
|
+
conditioning_scale: Optional[float] = 1.0,
|
1847
|
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
1848
|
+
attention_mask: Optional[Tensor] = None,
|
1849
|
+
upsample_size: Optional[int] = None,
|
1850
|
+
encoder_attention_mask: Optional[Tensor] = None,
|
1851
|
+
apply_control: bool = True,
|
1852
|
+
) -> Tensor:
|
1853
|
+
if cross_attention_kwargs is not None:
|
1854
|
+
if cross_attention_kwargs.get("scale", None) is not None:
|
1855
|
+
logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
|
1856
|
+
|
1857
|
+
is_freeu_enabled = (
|
1858
|
+
getattr(self, "s1", None)
|
1859
|
+
and getattr(self, "s2", None)
|
1860
|
+
and getattr(self, "b1", None)
|
1861
|
+
and getattr(self, "b2", None)
|
1862
|
+
)
|
1863
|
+
|
1864
|
+
def create_custom_forward(module, return_dict=None):
|
1865
|
+
def custom_forward(*inputs):
|
1866
|
+
if return_dict is not None:
|
1867
|
+
return module(*inputs, return_dict=return_dict)
|
1868
|
+
else:
|
1869
|
+
return module(*inputs)
|
1870
|
+
|
1871
|
+
return custom_forward
|
1872
|
+
|
1873
|
+
def maybe_apply_freeu_to_subblock(hidden_states, res_h_base):
|
1874
|
+
# FreeU: Only operate on the first two stages
|
1875
|
+
if is_freeu_enabled:
|
1876
|
+
return apply_freeu(
|
1877
|
+
self.resolution_idx,
|
1878
|
+
hidden_states,
|
1879
|
+
res_h_base,
|
1880
|
+
s1=self.s1,
|
1881
|
+
s2=self.s2,
|
1882
|
+
b1=self.b1,
|
1883
|
+
b2=self.b2,
|
1884
|
+
)
|
1885
|
+
else:
|
1886
|
+
return hidden_states, res_h_base
|
1887
|
+
|
1888
|
+
for resnet, attn, c2b, res_h_base, res_h_ctrl in zip(
|
1889
|
+
self.resnets,
|
1890
|
+
self.attentions,
|
1891
|
+
self.ctrl_to_base,
|
1892
|
+
reversed(res_hidden_states_tuple_base),
|
1893
|
+
reversed(res_hidden_states_tuple_ctrl),
|
1894
|
+
):
|
1895
|
+
if apply_control:
|
1896
|
+
hidden_states += c2b(res_h_ctrl) * conditioning_scale
|
1897
|
+
|
1898
|
+
hidden_states, res_h_base = maybe_apply_freeu_to_subblock(hidden_states, res_h_base)
|
1899
|
+
hidden_states = torch.cat([hidden_states, res_h_base], dim=1)
|
1900
|
+
|
1901
|
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
1902
|
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
1903
|
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
1904
|
+
create_custom_forward(resnet),
|
1905
|
+
hidden_states,
|
1906
|
+
temb,
|
1907
|
+
**ckpt_kwargs,
|
1908
|
+
)
|
1909
|
+
else:
|
1910
|
+
hidden_states = resnet(hidden_states, temb)
|
1911
|
+
|
1912
|
+
if attn is not None:
|
1913
|
+
hidden_states = attn(
|
1914
|
+
hidden_states,
|
1915
|
+
encoder_hidden_states=encoder_hidden_states,
|
1916
|
+
cross_attention_kwargs=cross_attention_kwargs,
|
1917
|
+
attention_mask=attention_mask,
|
1918
|
+
encoder_attention_mask=encoder_attention_mask,
|
1919
|
+
return_dict=False,
|
1920
|
+
)[0]
|
1921
|
+
|
1922
|
+
if self.upsamplers is not None:
|
1923
|
+
hidden_states = self.upsamplers(hidden_states, upsample_size)
|
1924
|
+
|
1925
|
+
return hidden_states
|
1926
|
+
|
1927
|
+
|
1928
|
+
def make_zero_conv(in_channels, out_channels=None):
|
1929
|
+
return zero_module(nn.Conv2d(in_channels, out_channels, 1, padding=0))
|
1930
|
+
|
1931
|
+
|
1932
|
+
def zero_module(module):
|
1933
|
+
for p in module.parameters():
|
1934
|
+
nn.init.zeros_(p)
|
1935
|
+
return module
|
1936
|
+
|
1937
|
+
|
1938
|
+
def find_largest_factor(number, max_factor):
|
1939
|
+
factor = max_factor
|
1940
|
+
if factor >= number:
|
1941
|
+
return number
|
1942
|
+
while factor != 0:
|
1943
|
+
residual = number % factor
|
1944
|
+
if residual == 0:
|
1945
|
+
return factor
|
1946
|
+
factor -= 1
|