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,1501 @@
|
|
1
|
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
|
15
|
+
|
16
|
+
import inspect
|
17
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
18
|
+
|
19
|
+
import numpy as np
|
20
|
+
import PIL.Image
|
21
|
+
import torch
|
22
|
+
import torch.nn.functional as F
|
23
|
+
from transformers import (
|
24
|
+
CLIPImageProcessor,
|
25
|
+
CLIPTextModel,
|
26
|
+
CLIPTextModelWithProjection,
|
27
|
+
CLIPTokenizer,
|
28
|
+
CLIPVisionModelWithProjection,
|
29
|
+
)
|
30
|
+
|
31
|
+
from diffusers.utils.import_utils import is_invisible_watermark_available
|
32
|
+
|
33
|
+
from ...callbacks import MultiPipelineCallbacks, PipelineCallback
|
34
|
+
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
35
|
+
from ...loaders import (
|
36
|
+
FromSingleFileMixin,
|
37
|
+
IPAdapterMixin,
|
38
|
+
StableDiffusionXLLoraLoaderMixin,
|
39
|
+
TextualInversionLoaderMixin,
|
40
|
+
)
|
41
|
+
from ...models import AutoencoderKL, ControlNetModel, ControlNetUnionModel, ImageProjection, UNet2DConditionModel
|
42
|
+
from ...models.attention_processor import (
|
43
|
+
AttnProcessor2_0,
|
44
|
+
XFormersAttnProcessor,
|
45
|
+
)
|
46
|
+
from ...models.lora import adjust_lora_scale_text_encoder
|
47
|
+
from ...schedulers import KarrasDiffusionSchedulers
|
48
|
+
from ...utils import (
|
49
|
+
USE_PEFT_BACKEND,
|
50
|
+
logging,
|
51
|
+
replace_example_docstring,
|
52
|
+
scale_lora_layers,
|
53
|
+
unscale_lora_layers,
|
54
|
+
)
|
55
|
+
from ...utils.torch_utils import is_compiled_module, is_torch_version, randn_tensor
|
56
|
+
from ..pipeline_utils import DiffusionPipeline, StableDiffusionMixin
|
57
|
+
from ..stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
|
58
|
+
|
59
|
+
|
60
|
+
if is_invisible_watermark_available():
|
61
|
+
from ..stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
|
62
|
+
|
63
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
64
|
+
|
65
|
+
|
66
|
+
EXAMPLE_DOC_STRING = """
|
67
|
+
Examples:
|
68
|
+
```py
|
69
|
+
>>> # !pip install controlnet_aux
|
70
|
+
>>> from controlnet_aux import LineartAnimeDetector
|
71
|
+
>>> from diffusers import StableDiffusionXLControlNetUnionPipeline, ControlNetUnionModel, AutoencoderKL
|
72
|
+
>>> from diffusers.utils import load_image
|
73
|
+
>>> import torch
|
74
|
+
|
75
|
+
>>> prompt = "A cat"
|
76
|
+
>>> # download an image
|
77
|
+
>>> image = load_image(
|
78
|
+
... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png"
|
79
|
+
... ).resize((1024, 1024))
|
80
|
+
>>> # initialize the models and pipeline
|
81
|
+
>>> controlnet = ControlNetUnionModel.from_pretrained(
|
82
|
+
... "xinsir/controlnet-union-sdxl-1.0", torch_dtype=torch.float16
|
83
|
+
... )
|
84
|
+
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
|
85
|
+
>>> pipe = StableDiffusionXLControlNetUnionPipeline.from_pretrained(
|
86
|
+
... "stabilityai/stable-diffusion-xl-base-1.0",
|
87
|
+
... controlnet=controlnet,
|
88
|
+
... vae=vae,
|
89
|
+
... torch_dtype=torch.float16,
|
90
|
+
... variant="fp16",
|
91
|
+
... )
|
92
|
+
>>> pipe.enable_model_cpu_offload()
|
93
|
+
>>> # prepare image
|
94
|
+
>>> processor = LineartAnimeDetector.from_pretrained("lllyasviel/Annotators")
|
95
|
+
>>> controlnet_img = processor(image, output_type="pil")
|
96
|
+
>>> # generate image
|
97
|
+
>>> image = pipe(prompt, control_image=[controlnet_img], control_mode=[3], height=1024, width=1024).images[0]
|
98
|
+
```
|
99
|
+
"""
|
100
|
+
|
101
|
+
|
102
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
103
|
+
def retrieve_timesteps(
|
104
|
+
scheduler,
|
105
|
+
num_inference_steps: Optional[int] = None,
|
106
|
+
device: Optional[Union[str, torch.device]] = None,
|
107
|
+
timesteps: Optional[List[int]] = None,
|
108
|
+
sigmas: Optional[List[float]] = None,
|
109
|
+
**kwargs,
|
110
|
+
):
|
111
|
+
r"""
|
112
|
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
113
|
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
114
|
+
|
115
|
+
Args:
|
116
|
+
scheduler (`SchedulerMixin`):
|
117
|
+
The scheduler to get timesteps from.
|
118
|
+
num_inference_steps (`int`):
|
119
|
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
120
|
+
must be `None`.
|
121
|
+
device (`str` or `torch.device`, *optional*):
|
122
|
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
123
|
+
timesteps (`List[int]`, *optional*):
|
124
|
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
125
|
+
`num_inference_steps` and `sigmas` must be `None`.
|
126
|
+
sigmas (`List[float]`, *optional*):
|
127
|
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
128
|
+
`num_inference_steps` and `timesteps` must be `None`.
|
129
|
+
|
130
|
+
Returns:
|
131
|
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
132
|
+
second element is the number of inference steps.
|
133
|
+
"""
|
134
|
+
if timesteps is not None and sigmas is not None:
|
135
|
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
136
|
+
if timesteps is not None:
|
137
|
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
138
|
+
if not accepts_timesteps:
|
139
|
+
raise ValueError(
|
140
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
141
|
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
142
|
+
)
|
143
|
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
144
|
+
timesteps = scheduler.timesteps
|
145
|
+
num_inference_steps = len(timesteps)
|
146
|
+
elif sigmas is not None:
|
147
|
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
148
|
+
if not accept_sigmas:
|
149
|
+
raise ValueError(
|
150
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
151
|
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
152
|
+
)
|
153
|
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
154
|
+
timesteps = scheduler.timesteps
|
155
|
+
num_inference_steps = len(timesteps)
|
156
|
+
else:
|
157
|
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
158
|
+
timesteps = scheduler.timesteps
|
159
|
+
return timesteps, num_inference_steps
|
160
|
+
|
161
|
+
|
162
|
+
class StableDiffusionXLControlNetUnionPipeline(
|
163
|
+
DiffusionPipeline,
|
164
|
+
StableDiffusionMixin,
|
165
|
+
TextualInversionLoaderMixin,
|
166
|
+
StableDiffusionXLLoraLoaderMixin,
|
167
|
+
IPAdapterMixin,
|
168
|
+
FromSingleFileMixin,
|
169
|
+
):
|
170
|
+
r"""
|
171
|
+
Pipeline for text-to-image generation using Stable Diffusion XL with ControlNet guidance.
|
172
|
+
|
173
|
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
174
|
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
175
|
+
|
176
|
+
The pipeline also inherits the following loading methods:
|
177
|
+
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
178
|
+
- [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
179
|
+
- [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
180
|
+
- [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
|
181
|
+
- [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
|
182
|
+
|
183
|
+
Args:
|
184
|
+
vae ([`AutoencoderKL`]):
|
185
|
+
Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
|
186
|
+
text_encoder ([`~transformers.CLIPTextModel`]):
|
187
|
+
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
188
|
+
text_encoder_2 ([`~transformers.CLIPTextModelWithProjection`]):
|
189
|
+
Second frozen text-encoder
|
190
|
+
([laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)).
|
191
|
+
tokenizer ([`~transformers.CLIPTokenizer`]):
|
192
|
+
A `CLIPTokenizer` to tokenize text.
|
193
|
+
tokenizer_2 ([`~transformers.CLIPTokenizer`]):
|
194
|
+
A `CLIPTokenizer` to tokenize text.
|
195
|
+
unet ([`UNet2DConditionModel`]):
|
196
|
+
A `UNet2DConditionModel` to denoise the encoded image latents.
|
197
|
+
controlnet ([`ControlNetUnionModel`]`):
|
198
|
+
Provides additional conditioning to the `unet` during the denoising process.
|
199
|
+
scheduler ([`SchedulerMixin`]):
|
200
|
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
201
|
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
202
|
+
force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
|
203
|
+
Whether the negative prompt embeddings should always be set to 0. Also see the config of
|
204
|
+
`stabilityai/stable-diffusion-xl-base-1-0`.
|
205
|
+
add_watermarker (`bool`, *optional*):
|
206
|
+
Whether to use the [invisible_watermark](https://github.com/ShieldMnt/invisible-watermark/) library to
|
207
|
+
watermark output images. If not defined, it defaults to `True` if the package is installed; otherwise no
|
208
|
+
watermarker is used.
|
209
|
+
"""
|
210
|
+
|
211
|
+
# leave controlnet out on purpose because it iterates with unet
|
212
|
+
model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
|
213
|
+
_optional_components = [
|
214
|
+
"tokenizer",
|
215
|
+
"tokenizer_2",
|
216
|
+
"text_encoder",
|
217
|
+
"text_encoder_2",
|
218
|
+
"feature_extractor",
|
219
|
+
"image_encoder",
|
220
|
+
]
|
221
|
+
_callback_tensor_inputs = [
|
222
|
+
"latents",
|
223
|
+
"prompt_embeds",
|
224
|
+
"add_text_embeds",
|
225
|
+
"add_time_ids",
|
226
|
+
]
|
227
|
+
|
228
|
+
def __init__(
|
229
|
+
self,
|
230
|
+
vae: AutoencoderKL,
|
231
|
+
text_encoder: CLIPTextModel,
|
232
|
+
text_encoder_2: CLIPTextModelWithProjection,
|
233
|
+
tokenizer: CLIPTokenizer,
|
234
|
+
tokenizer_2: CLIPTokenizer,
|
235
|
+
unet: UNet2DConditionModel,
|
236
|
+
controlnet: ControlNetUnionModel,
|
237
|
+
scheduler: KarrasDiffusionSchedulers,
|
238
|
+
force_zeros_for_empty_prompt: bool = True,
|
239
|
+
add_watermarker: Optional[bool] = None,
|
240
|
+
feature_extractor: CLIPImageProcessor = None,
|
241
|
+
image_encoder: CLIPVisionModelWithProjection = None,
|
242
|
+
):
|
243
|
+
super().__init__()
|
244
|
+
|
245
|
+
if not isinstance(controlnet, ControlNetUnionModel):
|
246
|
+
raise ValueError("Expected `controlnet` to be of type `ControlNetUnionModel`.")
|
247
|
+
|
248
|
+
self.register_modules(
|
249
|
+
vae=vae,
|
250
|
+
text_encoder=text_encoder,
|
251
|
+
text_encoder_2=text_encoder_2,
|
252
|
+
tokenizer=tokenizer,
|
253
|
+
tokenizer_2=tokenizer_2,
|
254
|
+
unet=unet,
|
255
|
+
controlnet=controlnet,
|
256
|
+
scheduler=scheduler,
|
257
|
+
feature_extractor=feature_extractor,
|
258
|
+
image_encoder=image_encoder,
|
259
|
+
)
|
260
|
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
261
|
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
|
262
|
+
self.control_image_processor = VaeImageProcessor(
|
263
|
+
vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
|
264
|
+
)
|
265
|
+
add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
|
266
|
+
|
267
|
+
if add_watermarker:
|
268
|
+
self.watermark = StableDiffusionXLWatermarker()
|
269
|
+
else:
|
270
|
+
self.watermark = None
|
271
|
+
|
272
|
+
self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
|
273
|
+
|
274
|
+
# Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
|
275
|
+
def encode_prompt(
|
276
|
+
self,
|
277
|
+
prompt: str,
|
278
|
+
prompt_2: Optional[str] = None,
|
279
|
+
device: Optional[torch.device] = None,
|
280
|
+
num_images_per_prompt: int = 1,
|
281
|
+
do_classifier_free_guidance: bool = True,
|
282
|
+
negative_prompt: Optional[str] = None,
|
283
|
+
negative_prompt_2: Optional[str] = None,
|
284
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
285
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
286
|
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
287
|
+
negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
288
|
+
lora_scale: Optional[float] = None,
|
289
|
+
clip_skip: Optional[int] = None,
|
290
|
+
):
|
291
|
+
r"""
|
292
|
+
Encodes the prompt into text encoder hidden states.
|
293
|
+
|
294
|
+
Args:
|
295
|
+
prompt (`str` or `List[str]`, *optional*):
|
296
|
+
prompt to be encoded
|
297
|
+
prompt_2 (`str` or `List[str]`, *optional*):
|
298
|
+
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
299
|
+
used in both text-encoders
|
300
|
+
device: (`torch.device`):
|
301
|
+
torch device
|
302
|
+
num_images_per_prompt (`int`):
|
303
|
+
number of images that should be generated per prompt
|
304
|
+
do_classifier_free_guidance (`bool`):
|
305
|
+
whether to use classifier free guidance or not
|
306
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
307
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
308
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
309
|
+
less than `1`).
|
310
|
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
311
|
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
312
|
+
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
313
|
+
prompt_embeds (`torch.Tensor`, *optional*):
|
314
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
315
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
316
|
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
317
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
318
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
319
|
+
argument.
|
320
|
+
pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
321
|
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
322
|
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
323
|
+
negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
324
|
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
325
|
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
326
|
+
input argument.
|
327
|
+
lora_scale (`float`, *optional*):
|
328
|
+
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
329
|
+
clip_skip (`int`, *optional*):
|
330
|
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
331
|
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
332
|
+
"""
|
333
|
+
device = device or self._execution_device
|
334
|
+
|
335
|
+
# set lora scale so that monkey patched LoRA
|
336
|
+
# function of text encoder can correctly access it
|
337
|
+
if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
|
338
|
+
self._lora_scale = lora_scale
|
339
|
+
|
340
|
+
# dynamically adjust the LoRA scale
|
341
|
+
if self.text_encoder is not None:
|
342
|
+
if not USE_PEFT_BACKEND:
|
343
|
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
344
|
+
else:
|
345
|
+
scale_lora_layers(self.text_encoder, lora_scale)
|
346
|
+
|
347
|
+
if self.text_encoder_2 is not None:
|
348
|
+
if not USE_PEFT_BACKEND:
|
349
|
+
adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
|
350
|
+
else:
|
351
|
+
scale_lora_layers(self.text_encoder_2, lora_scale)
|
352
|
+
|
353
|
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
354
|
+
|
355
|
+
if prompt is not None:
|
356
|
+
batch_size = len(prompt)
|
357
|
+
else:
|
358
|
+
batch_size = prompt_embeds.shape[0]
|
359
|
+
|
360
|
+
# Define tokenizers and text encoders
|
361
|
+
tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
|
362
|
+
text_encoders = (
|
363
|
+
[self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
|
364
|
+
)
|
365
|
+
|
366
|
+
if prompt_embeds is None:
|
367
|
+
prompt_2 = prompt_2 or prompt
|
368
|
+
prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
|
369
|
+
|
370
|
+
# textual inversion: process multi-vector tokens if necessary
|
371
|
+
prompt_embeds_list = []
|
372
|
+
prompts = [prompt, prompt_2]
|
373
|
+
for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
|
374
|
+
if isinstance(self, TextualInversionLoaderMixin):
|
375
|
+
prompt = self.maybe_convert_prompt(prompt, tokenizer)
|
376
|
+
|
377
|
+
text_inputs = tokenizer(
|
378
|
+
prompt,
|
379
|
+
padding="max_length",
|
380
|
+
max_length=tokenizer.model_max_length,
|
381
|
+
truncation=True,
|
382
|
+
return_tensors="pt",
|
383
|
+
)
|
384
|
+
|
385
|
+
text_input_ids = text_inputs.input_ids
|
386
|
+
untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
387
|
+
|
388
|
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
389
|
+
text_input_ids, untruncated_ids
|
390
|
+
):
|
391
|
+
removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
|
392
|
+
logger.warning(
|
393
|
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
394
|
+
f" {tokenizer.model_max_length} tokens: {removed_text}"
|
395
|
+
)
|
396
|
+
|
397
|
+
prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
|
398
|
+
|
399
|
+
# We are only ALWAYS interested in the pooled output of the final text encoder
|
400
|
+
pooled_prompt_embeds = prompt_embeds[0]
|
401
|
+
if clip_skip is None:
|
402
|
+
prompt_embeds = prompt_embeds.hidden_states[-2]
|
403
|
+
else:
|
404
|
+
# "2" because SDXL always indexes from the penultimate layer.
|
405
|
+
prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
|
406
|
+
|
407
|
+
prompt_embeds_list.append(prompt_embeds)
|
408
|
+
|
409
|
+
prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
|
410
|
+
|
411
|
+
# get unconditional embeddings for classifier free guidance
|
412
|
+
zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
|
413
|
+
if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
|
414
|
+
negative_prompt_embeds = torch.zeros_like(prompt_embeds)
|
415
|
+
negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
|
416
|
+
elif do_classifier_free_guidance and negative_prompt_embeds is None:
|
417
|
+
negative_prompt = negative_prompt or ""
|
418
|
+
negative_prompt_2 = negative_prompt_2 or negative_prompt
|
419
|
+
|
420
|
+
# normalize str to list
|
421
|
+
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
422
|
+
negative_prompt_2 = (
|
423
|
+
batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
|
424
|
+
)
|
425
|
+
|
426
|
+
uncond_tokens: List[str]
|
427
|
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
428
|
+
raise TypeError(
|
429
|
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
430
|
+
f" {type(prompt)}."
|
431
|
+
)
|
432
|
+
elif batch_size != len(negative_prompt):
|
433
|
+
raise ValueError(
|
434
|
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
435
|
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
436
|
+
" the batch size of `prompt`."
|
437
|
+
)
|
438
|
+
else:
|
439
|
+
uncond_tokens = [negative_prompt, negative_prompt_2]
|
440
|
+
|
441
|
+
negative_prompt_embeds_list = []
|
442
|
+
for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
|
443
|
+
if isinstance(self, TextualInversionLoaderMixin):
|
444
|
+
negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
|
445
|
+
|
446
|
+
max_length = prompt_embeds.shape[1]
|
447
|
+
uncond_input = tokenizer(
|
448
|
+
negative_prompt,
|
449
|
+
padding="max_length",
|
450
|
+
max_length=max_length,
|
451
|
+
truncation=True,
|
452
|
+
return_tensors="pt",
|
453
|
+
)
|
454
|
+
|
455
|
+
negative_prompt_embeds = text_encoder(
|
456
|
+
uncond_input.input_ids.to(device),
|
457
|
+
output_hidden_states=True,
|
458
|
+
)
|
459
|
+
# We are only ALWAYS interested in the pooled output of the final text encoder
|
460
|
+
negative_pooled_prompt_embeds = negative_prompt_embeds[0]
|
461
|
+
negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
|
462
|
+
|
463
|
+
negative_prompt_embeds_list.append(negative_prompt_embeds)
|
464
|
+
|
465
|
+
negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
|
466
|
+
|
467
|
+
if self.text_encoder_2 is not None:
|
468
|
+
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
|
469
|
+
else:
|
470
|
+
prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
|
471
|
+
|
472
|
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
473
|
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
474
|
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
475
|
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
476
|
+
|
477
|
+
if do_classifier_free_guidance:
|
478
|
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
479
|
+
seq_len = negative_prompt_embeds.shape[1]
|
480
|
+
|
481
|
+
if self.text_encoder_2 is not None:
|
482
|
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
|
483
|
+
else:
|
484
|
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
|
485
|
+
|
486
|
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
487
|
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
488
|
+
|
489
|
+
pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
490
|
+
bs_embed * num_images_per_prompt, -1
|
491
|
+
)
|
492
|
+
if do_classifier_free_guidance:
|
493
|
+
negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
494
|
+
bs_embed * num_images_per_prompt, -1
|
495
|
+
)
|
496
|
+
|
497
|
+
if self.text_encoder is not None:
|
498
|
+
if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
|
499
|
+
# Retrieve the original scale by scaling back the LoRA layers
|
500
|
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
501
|
+
|
502
|
+
if self.text_encoder_2 is not None:
|
503
|
+
if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
|
504
|
+
# Retrieve the original scale by scaling back the LoRA layers
|
505
|
+
unscale_lora_layers(self.text_encoder_2, lora_scale)
|
506
|
+
|
507
|
+
return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
|
508
|
+
|
509
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
|
510
|
+
def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
|
511
|
+
dtype = next(self.image_encoder.parameters()).dtype
|
512
|
+
|
513
|
+
if not isinstance(image, torch.Tensor):
|
514
|
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
515
|
+
|
516
|
+
image = image.to(device=device, dtype=dtype)
|
517
|
+
if output_hidden_states:
|
518
|
+
image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
|
519
|
+
image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
|
520
|
+
uncond_image_enc_hidden_states = self.image_encoder(
|
521
|
+
torch.zeros_like(image), output_hidden_states=True
|
522
|
+
).hidden_states[-2]
|
523
|
+
uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
|
524
|
+
num_images_per_prompt, dim=0
|
525
|
+
)
|
526
|
+
return image_enc_hidden_states, uncond_image_enc_hidden_states
|
527
|
+
else:
|
528
|
+
image_embeds = self.image_encoder(image).image_embeds
|
529
|
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
530
|
+
uncond_image_embeds = torch.zeros_like(image_embeds)
|
531
|
+
|
532
|
+
return image_embeds, uncond_image_embeds
|
533
|
+
|
534
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
|
535
|
+
def prepare_ip_adapter_image_embeds(
|
536
|
+
self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
|
537
|
+
):
|
538
|
+
image_embeds = []
|
539
|
+
if do_classifier_free_guidance:
|
540
|
+
negative_image_embeds = []
|
541
|
+
if ip_adapter_image_embeds is None:
|
542
|
+
if not isinstance(ip_adapter_image, list):
|
543
|
+
ip_adapter_image = [ip_adapter_image]
|
544
|
+
|
545
|
+
if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
|
546
|
+
raise ValueError(
|
547
|
+
f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
|
548
|
+
)
|
549
|
+
|
550
|
+
for single_ip_adapter_image, image_proj_layer in zip(
|
551
|
+
ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
|
552
|
+
):
|
553
|
+
output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
|
554
|
+
single_image_embeds, single_negative_image_embeds = self.encode_image(
|
555
|
+
single_ip_adapter_image, device, 1, output_hidden_state
|
556
|
+
)
|
557
|
+
|
558
|
+
image_embeds.append(single_image_embeds[None, :])
|
559
|
+
if do_classifier_free_guidance:
|
560
|
+
negative_image_embeds.append(single_negative_image_embeds[None, :])
|
561
|
+
else:
|
562
|
+
for single_image_embeds in ip_adapter_image_embeds:
|
563
|
+
if do_classifier_free_guidance:
|
564
|
+
single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
|
565
|
+
negative_image_embeds.append(single_negative_image_embeds)
|
566
|
+
image_embeds.append(single_image_embeds)
|
567
|
+
|
568
|
+
ip_adapter_image_embeds = []
|
569
|
+
for i, single_image_embeds in enumerate(image_embeds):
|
570
|
+
single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
|
571
|
+
if do_classifier_free_guidance:
|
572
|
+
single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
|
573
|
+
single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
|
574
|
+
|
575
|
+
single_image_embeds = single_image_embeds.to(device=device)
|
576
|
+
ip_adapter_image_embeds.append(single_image_embeds)
|
577
|
+
|
578
|
+
return ip_adapter_image_embeds
|
579
|
+
|
580
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
581
|
+
def prepare_extra_step_kwargs(self, generator, eta):
|
582
|
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
583
|
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
584
|
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
585
|
+
# and should be between [0, 1]
|
586
|
+
|
587
|
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
588
|
+
extra_step_kwargs = {}
|
589
|
+
if accepts_eta:
|
590
|
+
extra_step_kwargs["eta"] = eta
|
591
|
+
|
592
|
+
# check if the scheduler accepts generator
|
593
|
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
594
|
+
if accepts_generator:
|
595
|
+
extra_step_kwargs["generator"] = generator
|
596
|
+
return extra_step_kwargs
|
597
|
+
|
598
|
+
# Copied from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl.StableDiffusionXLControlNetPipeline.check_image
|
599
|
+
def check_image(self, image, prompt, prompt_embeds):
|
600
|
+
image_is_pil = isinstance(image, PIL.Image.Image)
|
601
|
+
image_is_tensor = isinstance(image, torch.Tensor)
|
602
|
+
image_is_np = isinstance(image, np.ndarray)
|
603
|
+
image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
|
604
|
+
image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
|
605
|
+
image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
|
606
|
+
|
607
|
+
if (
|
608
|
+
not image_is_pil
|
609
|
+
and not image_is_tensor
|
610
|
+
and not image_is_np
|
611
|
+
and not image_is_pil_list
|
612
|
+
and not image_is_tensor_list
|
613
|
+
and not image_is_np_list
|
614
|
+
):
|
615
|
+
raise TypeError(
|
616
|
+
f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
|
617
|
+
)
|
618
|
+
|
619
|
+
if image_is_pil:
|
620
|
+
image_batch_size = 1
|
621
|
+
else:
|
622
|
+
image_batch_size = len(image)
|
623
|
+
|
624
|
+
if prompt is not None and isinstance(prompt, str):
|
625
|
+
prompt_batch_size = 1
|
626
|
+
elif prompt is not None and isinstance(prompt, list):
|
627
|
+
prompt_batch_size = len(prompt)
|
628
|
+
elif prompt_embeds is not None:
|
629
|
+
prompt_batch_size = prompt_embeds.shape[0]
|
630
|
+
|
631
|
+
if image_batch_size != 1 and image_batch_size != prompt_batch_size:
|
632
|
+
raise ValueError(
|
633
|
+
f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
|
634
|
+
)
|
635
|
+
|
636
|
+
def check_inputs(
|
637
|
+
self,
|
638
|
+
prompt,
|
639
|
+
prompt_2,
|
640
|
+
image: PipelineImageInput,
|
641
|
+
negative_prompt=None,
|
642
|
+
negative_prompt_2=None,
|
643
|
+
prompt_embeds=None,
|
644
|
+
negative_prompt_embeds=None,
|
645
|
+
pooled_prompt_embeds=None,
|
646
|
+
ip_adapter_image=None,
|
647
|
+
ip_adapter_image_embeds=None,
|
648
|
+
negative_pooled_prompt_embeds=None,
|
649
|
+
controlnet_conditioning_scale=1.0,
|
650
|
+
control_guidance_start=0.0,
|
651
|
+
control_guidance_end=1.0,
|
652
|
+
callback_on_step_end_tensor_inputs=None,
|
653
|
+
):
|
654
|
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
655
|
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
656
|
+
):
|
657
|
+
raise ValueError(
|
658
|
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
659
|
+
)
|
660
|
+
|
661
|
+
if prompt is not None and prompt_embeds is not None:
|
662
|
+
raise ValueError(
|
663
|
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
664
|
+
" only forward one of the two."
|
665
|
+
)
|
666
|
+
elif prompt_2 is not None and prompt_embeds is not None:
|
667
|
+
raise ValueError(
|
668
|
+
f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
669
|
+
" only forward one of the two."
|
670
|
+
)
|
671
|
+
elif prompt is None and prompt_embeds is None:
|
672
|
+
raise ValueError(
|
673
|
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
674
|
+
)
|
675
|
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
676
|
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
677
|
+
elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
|
678
|
+
raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
|
679
|
+
|
680
|
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
681
|
+
raise ValueError(
|
682
|
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
683
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
684
|
+
)
|
685
|
+
elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
|
686
|
+
raise ValueError(
|
687
|
+
f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
|
688
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
689
|
+
)
|
690
|
+
|
691
|
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
692
|
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
693
|
+
raise ValueError(
|
694
|
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
695
|
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
696
|
+
f" {negative_prompt_embeds.shape}."
|
697
|
+
)
|
698
|
+
|
699
|
+
if prompt_embeds is not None and pooled_prompt_embeds is None:
|
700
|
+
raise ValueError(
|
701
|
+
"If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
|
702
|
+
)
|
703
|
+
|
704
|
+
if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
|
705
|
+
raise ValueError(
|
706
|
+
"If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
|
707
|
+
)
|
708
|
+
|
709
|
+
# Check `image`
|
710
|
+
is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
|
711
|
+
self.controlnet, torch._dynamo.eval_frame.OptimizedModule
|
712
|
+
)
|
713
|
+
if (
|
714
|
+
isinstance(self.controlnet, ControlNetModel)
|
715
|
+
or is_compiled
|
716
|
+
and isinstance(self.controlnet._orig_mod, ControlNetModel)
|
717
|
+
):
|
718
|
+
self.check_image(image, prompt, prompt_embeds)
|
719
|
+
elif (
|
720
|
+
isinstance(self.controlnet, ControlNetUnionModel)
|
721
|
+
or is_compiled
|
722
|
+
and isinstance(self.controlnet._orig_mod, ControlNetUnionModel)
|
723
|
+
):
|
724
|
+
self.check_image(image, prompt, prompt_embeds)
|
725
|
+
|
726
|
+
else:
|
727
|
+
assert False
|
728
|
+
|
729
|
+
# Check `controlnet_conditioning_scale`
|
730
|
+
if (
|
731
|
+
isinstance(self.controlnet, ControlNetModel)
|
732
|
+
or is_compiled
|
733
|
+
and isinstance(self.controlnet._orig_mod, ControlNetModel)
|
734
|
+
):
|
735
|
+
if not isinstance(controlnet_conditioning_scale, float):
|
736
|
+
raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
|
737
|
+
|
738
|
+
elif (
|
739
|
+
isinstance(self.controlnet, ControlNetUnionModel)
|
740
|
+
or is_compiled
|
741
|
+
and isinstance(self.controlnet._orig_mod, ControlNetUnionModel)
|
742
|
+
):
|
743
|
+
if not isinstance(controlnet_conditioning_scale, float):
|
744
|
+
raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
|
745
|
+
|
746
|
+
else:
|
747
|
+
assert False
|
748
|
+
|
749
|
+
if not isinstance(control_guidance_start, (tuple, list)):
|
750
|
+
control_guidance_start = [control_guidance_start]
|
751
|
+
|
752
|
+
if not isinstance(control_guidance_end, (tuple, list)):
|
753
|
+
control_guidance_end = [control_guidance_end]
|
754
|
+
|
755
|
+
if len(control_guidance_start) != len(control_guidance_end):
|
756
|
+
raise ValueError(
|
757
|
+
f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list."
|
758
|
+
)
|
759
|
+
|
760
|
+
for start, end in zip(control_guidance_start, control_guidance_end):
|
761
|
+
if start >= end:
|
762
|
+
raise ValueError(
|
763
|
+
f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
|
764
|
+
)
|
765
|
+
if start < 0.0:
|
766
|
+
raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
|
767
|
+
if end > 1.0:
|
768
|
+
raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
|
769
|
+
|
770
|
+
if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
|
771
|
+
raise ValueError(
|
772
|
+
"Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
|
773
|
+
)
|
774
|
+
|
775
|
+
if ip_adapter_image_embeds is not None:
|
776
|
+
if not isinstance(ip_adapter_image_embeds, list):
|
777
|
+
raise ValueError(
|
778
|
+
f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
|
779
|
+
)
|
780
|
+
elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
|
781
|
+
raise ValueError(
|
782
|
+
f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
|
783
|
+
)
|
784
|
+
|
785
|
+
# Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.prepare_image
|
786
|
+
def prepare_image(
|
787
|
+
self,
|
788
|
+
image,
|
789
|
+
width,
|
790
|
+
height,
|
791
|
+
batch_size,
|
792
|
+
num_images_per_prompt,
|
793
|
+
device,
|
794
|
+
dtype,
|
795
|
+
do_classifier_free_guidance=False,
|
796
|
+
guess_mode=False,
|
797
|
+
):
|
798
|
+
image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
|
799
|
+
image_batch_size = image.shape[0]
|
800
|
+
|
801
|
+
if image_batch_size == 1:
|
802
|
+
repeat_by = batch_size
|
803
|
+
else:
|
804
|
+
# image batch size is the same as prompt batch size
|
805
|
+
repeat_by = num_images_per_prompt
|
806
|
+
|
807
|
+
image = image.repeat_interleave(repeat_by, dim=0)
|
808
|
+
|
809
|
+
image = image.to(device=device, dtype=dtype)
|
810
|
+
|
811
|
+
if do_classifier_free_guidance and not guess_mode:
|
812
|
+
image = torch.cat([image] * 2)
|
813
|
+
|
814
|
+
return image
|
815
|
+
|
816
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
|
817
|
+
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
|
818
|
+
shape = (
|
819
|
+
batch_size,
|
820
|
+
num_channels_latents,
|
821
|
+
int(height) // self.vae_scale_factor,
|
822
|
+
int(width) // self.vae_scale_factor,
|
823
|
+
)
|
824
|
+
if isinstance(generator, list) and len(generator) != batch_size:
|
825
|
+
raise ValueError(
|
826
|
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
827
|
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
828
|
+
)
|
829
|
+
|
830
|
+
if latents is None:
|
831
|
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
832
|
+
else:
|
833
|
+
latents = latents.to(device)
|
834
|
+
|
835
|
+
# scale the initial noise by the standard deviation required by the scheduler
|
836
|
+
latents = latents * self.scheduler.init_noise_sigma
|
837
|
+
return latents
|
838
|
+
|
839
|
+
# Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline._get_add_time_ids
|
840
|
+
def _get_add_time_ids(
|
841
|
+
self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
|
842
|
+
):
|
843
|
+
add_time_ids = list(original_size + crops_coords_top_left + target_size)
|
844
|
+
|
845
|
+
passed_add_embed_dim = (
|
846
|
+
self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
|
847
|
+
)
|
848
|
+
expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
|
849
|
+
|
850
|
+
if expected_add_embed_dim != passed_add_embed_dim:
|
851
|
+
raise ValueError(
|
852
|
+
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
|
853
|
+
)
|
854
|
+
|
855
|
+
add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
|
856
|
+
return add_time_ids
|
857
|
+
|
858
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
|
859
|
+
def upcast_vae(self):
|
860
|
+
dtype = self.vae.dtype
|
861
|
+
self.vae.to(dtype=torch.float32)
|
862
|
+
use_torch_2_0_or_xformers = isinstance(
|
863
|
+
self.vae.decoder.mid_block.attentions[0].processor,
|
864
|
+
(
|
865
|
+
AttnProcessor2_0,
|
866
|
+
XFormersAttnProcessor,
|
867
|
+
),
|
868
|
+
)
|
869
|
+
# if xformers or torch_2_0 is used attention block does not need
|
870
|
+
# to be in float32 which can save lots of memory
|
871
|
+
if use_torch_2_0_or_xformers:
|
872
|
+
self.vae.post_quant_conv.to(dtype)
|
873
|
+
self.vae.decoder.conv_in.to(dtype)
|
874
|
+
self.vae.decoder.mid_block.to(dtype)
|
875
|
+
|
876
|
+
# Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
|
877
|
+
def get_guidance_scale_embedding(
|
878
|
+
self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
|
879
|
+
) -> torch.Tensor:
|
880
|
+
"""
|
881
|
+
See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
|
882
|
+
|
883
|
+
Args:
|
884
|
+
w (`torch.Tensor`):
|
885
|
+
Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
|
886
|
+
embedding_dim (`int`, *optional*, defaults to 512):
|
887
|
+
Dimension of the embeddings to generate.
|
888
|
+
dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
|
889
|
+
Data type of the generated embeddings.
|
890
|
+
|
891
|
+
Returns:
|
892
|
+
`torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
|
893
|
+
"""
|
894
|
+
assert len(w.shape) == 1
|
895
|
+
w = w * 1000.0
|
896
|
+
|
897
|
+
half_dim = embedding_dim // 2
|
898
|
+
emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
|
899
|
+
emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
|
900
|
+
emb = w.to(dtype)[:, None] * emb[None, :]
|
901
|
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
902
|
+
if embedding_dim % 2 == 1: # zero pad
|
903
|
+
emb = torch.nn.functional.pad(emb, (0, 1))
|
904
|
+
assert emb.shape == (w.shape[0], embedding_dim)
|
905
|
+
return emb
|
906
|
+
|
907
|
+
@property
|
908
|
+
def guidance_scale(self):
|
909
|
+
return self._guidance_scale
|
910
|
+
|
911
|
+
@property
|
912
|
+
def clip_skip(self):
|
913
|
+
return self._clip_skip
|
914
|
+
|
915
|
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
916
|
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
917
|
+
# corresponds to doing no classifier free guidance.
|
918
|
+
@property
|
919
|
+
def do_classifier_free_guidance(self):
|
920
|
+
return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
|
921
|
+
|
922
|
+
@property
|
923
|
+
def cross_attention_kwargs(self):
|
924
|
+
return self._cross_attention_kwargs
|
925
|
+
|
926
|
+
@property
|
927
|
+
def denoising_end(self):
|
928
|
+
return self._denoising_end
|
929
|
+
|
930
|
+
@property
|
931
|
+
def num_timesteps(self):
|
932
|
+
return self._num_timesteps
|
933
|
+
|
934
|
+
@property
|
935
|
+
def interrupt(self):
|
936
|
+
return self._interrupt
|
937
|
+
|
938
|
+
@torch.no_grad()
|
939
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
940
|
+
def __call__(
|
941
|
+
self,
|
942
|
+
prompt: Union[str, List[str]] = None,
|
943
|
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
944
|
+
control_image: PipelineImageInput = None,
|
945
|
+
height: Optional[int] = None,
|
946
|
+
width: Optional[int] = None,
|
947
|
+
num_inference_steps: int = 50,
|
948
|
+
timesteps: List[int] = None,
|
949
|
+
sigmas: List[float] = None,
|
950
|
+
denoising_end: Optional[float] = None,
|
951
|
+
guidance_scale: float = 5.0,
|
952
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
953
|
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
954
|
+
num_images_per_prompt: Optional[int] = 1,
|
955
|
+
eta: float = 0.0,
|
956
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
957
|
+
latents: Optional[torch.Tensor] = None,
|
958
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
959
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
960
|
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
961
|
+
negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
962
|
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
963
|
+
ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
|
964
|
+
output_type: Optional[str] = "pil",
|
965
|
+
return_dict: bool = True,
|
966
|
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
967
|
+
controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
|
968
|
+
guess_mode: bool = False,
|
969
|
+
control_guidance_start: Union[float, List[float]] = 0.0,
|
970
|
+
control_guidance_end: Union[float, List[float]] = 1.0,
|
971
|
+
control_mode: Optional[Union[int, List[int]]] = None,
|
972
|
+
original_size: Tuple[int, int] = None,
|
973
|
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
974
|
+
target_size: Tuple[int, int] = None,
|
975
|
+
negative_original_size: Optional[Tuple[int, int]] = None,
|
976
|
+
negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
|
977
|
+
negative_target_size: Optional[Tuple[int, int]] = None,
|
978
|
+
clip_skip: Optional[int] = None,
|
979
|
+
callback_on_step_end: Optional[
|
980
|
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
981
|
+
] = None,
|
982
|
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
983
|
+
):
|
984
|
+
r"""
|
985
|
+
The call function to the pipeline for generation.
|
986
|
+
|
987
|
+
Args:
|
988
|
+
prompt (`str` or `List[str]`, *optional*):
|
989
|
+
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
990
|
+
prompt_2 (`str` or `List[str]`, *optional*):
|
991
|
+
The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
992
|
+
used in both text-encoders.
|
993
|
+
control_image (`PipelineImageInput`):
|
994
|
+
The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
|
995
|
+
specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted
|
996
|
+
as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or
|
997
|
+
width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`,
|
998
|
+
images must be passed as a list such that each element of the list can be correctly batched for input
|
999
|
+
to a single ControlNet.
|
1000
|
+
height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
1001
|
+
The height in pixels of the generated image. Anything below 512 pixels won't work well for
|
1002
|
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
1003
|
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
1004
|
+
width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
1005
|
+
The width in pixels of the generated image. Anything below 512 pixels won't work well for
|
1006
|
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
1007
|
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
1008
|
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
1009
|
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
1010
|
+
expense of slower inference.
|
1011
|
+
timesteps (`List[int]`, *optional*):
|
1012
|
+
Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
|
1013
|
+
in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
|
1014
|
+
passed will be used. Must be in descending order.
|
1015
|
+
sigmas (`List[float]`, *optional*):
|
1016
|
+
Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
|
1017
|
+
their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
|
1018
|
+
will be used.
|
1019
|
+
denoising_end (`float`, *optional*):
|
1020
|
+
When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
|
1021
|
+
completed before it is intentionally prematurely terminated. As a result, the returned sample will
|
1022
|
+
still retain a substantial amount of noise as determined by the discrete timesteps selected by the
|
1023
|
+
scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
|
1024
|
+
"Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
|
1025
|
+
Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
|
1026
|
+
guidance_scale (`float`, *optional*, defaults to 5.0):
|
1027
|
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
1028
|
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
1029
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
1030
|
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
1031
|
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
1032
|
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
1033
|
+
The prompt or prompts to guide what to not include in image generation. This is sent to `tokenizer_2`
|
1034
|
+
and `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders.
|
1035
|
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
1036
|
+
The number of images to generate per prompt.
|
1037
|
+
eta (`float`, *optional*, defaults to 0.0):
|
1038
|
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
1039
|
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
1040
|
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
1041
|
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
1042
|
+
generation deterministic.
|
1043
|
+
latents (`torch.Tensor`, *optional*):
|
1044
|
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
1045
|
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
1046
|
+
tensor is generated by sampling using the supplied random `generator`.
|
1047
|
+
prompt_embeds (`torch.Tensor`, *optional*):
|
1048
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
1049
|
+
provided, text embeddings are generated from the `prompt` input argument.
|
1050
|
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
1051
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
1052
|
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
1053
|
+
pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
1054
|
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
1055
|
+
not provided, pooled text embeddings are generated from `prompt` input argument.
|
1056
|
+
negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
1057
|
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs (prompt
|
1058
|
+
weighting). If not provided, pooled `negative_prompt_embeds` are generated from `negative_prompt` input
|
1059
|
+
argument.
|
1060
|
+
ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
|
1061
|
+
ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
|
1062
|
+
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
|
1063
|
+
IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
|
1064
|
+
contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
|
1065
|
+
provided, embeddings are computed from the `ip_adapter_image` input argument.
|
1066
|
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
1067
|
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
1068
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
1069
|
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
1070
|
+
plain tuple.
|
1071
|
+
cross_attention_kwargs (`dict`, *optional*):
|
1072
|
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
1073
|
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
1074
|
+
controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
|
1075
|
+
The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
|
1076
|
+
to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
|
1077
|
+
the corresponding scale as a list.
|
1078
|
+
guess_mode (`bool`, *optional*, defaults to `False`):
|
1079
|
+
The ControlNet encoder tries to recognize the content of the input image even if you remove all
|
1080
|
+
prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
|
1081
|
+
control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
|
1082
|
+
The percentage of total steps at which the ControlNet starts applying.
|
1083
|
+
control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
|
1084
|
+
The percentage of total steps at which the ControlNet stops applying.
|
1085
|
+
original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
1086
|
+
If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
|
1087
|
+
`original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
|
1088
|
+
explained in section 2.2 of
|
1089
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
1090
|
+
crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
1091
|
+
`crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
|
1092
|
+
`crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
|
1093
|
+
`crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
|
1094
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
1095
|
+
target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
1096
|
+
For most cases, `target_size` should be set to the desired height and width of the generated image. If
|
1097
|
+
not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
|
1098
|
+
section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
1099
|
+
negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
1100
|
+
To negatively condition the generation process based on a specific image resolution. Part of SDXL's
|
1101
|
+
micro-conditioning as explained in section 2.2 of
|
1102
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
1103
|
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
1104
|
+
negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
1105
|
+
To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
|
1106
|
+
micro-conditioning as explained in section 2.2 of
|
1107
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
1108
|
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
1109
|
+
negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
1110
|
+
To negatively condition the generation process based on a target image resolution. It should be as same
|
1111
|
+
as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
|
1112
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
1113
|
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
1114
|
+
clip_skip (`int`, *optional*):
|
1115
|
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
1116
|
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
1117
|
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
1118
|
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
1119
|
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
1120
|
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
1121
|
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
1122
|
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
1123
|
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
1124
|
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
1125
|
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
1126
|
+
|
1127
|
+
Examples:
|
1128
|
+
|
1129
|
+
Returns:
|
1130
|
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
1131
|
+
If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
|
1132
|
+
otherwise a `tuple` is returned containing the output images.
|
1133
|
+
"""
|
1134
|
+
|
1135
|
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
1136
|
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
1137
|
+
|
1138
|
+
controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
|
1139
|
+
|
1140
|
+
# align format for control guidance
|
1141
|
+
if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
|
1142
|
+
control_guidance_start = len(control_guidance_end) * [control_guidance_start]
|
1143
|
+
elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
|
1144
|
+
control_guidance_end = len(control_guidance_start) * [control_guidance_end]
|
1145
|
+
|
1146
|
+
if not isinstance(control_image, list):
|
1147
|
+
control_image = [control_image]
|
1148
|
+
|
1149
|
+
if not isinstance(control_mode, list):
|
1150
|
+
control_mode = [control_mode]
|
1151
|
+
|
1152
|
+
if len(control_image) != len(control_mode):
|
1153
|
+
raise ValueError("Expected len(control_image) == len(control_type)")
|
1154
|
+
|
1155
|
+
num_control_type = controlnet.config.num_control_type
|
1156
|
+
|
1157
|
+
# 1. Check inputs
|
1158
|
+
control_type = [0 for _ in range(num_control_type)]
|
1159
|
+
# 1. Check inputs. Raise error if not correct
|
1160
|
+
for _image, control_idx in zip(control_image, control_mode):
|
1161
|
+
control_type[control_idx] = 1
|
1162
|
+
self.check_inputs(
|
1163
|
+
prompt,
|
1164
|
+
prompt_2,
|
1165
|
+
_image,
|
1166
|
+
negative_prompt,
|
1167
|
+
negative_prompt_2,
|
1168
|
+
prompt_embeds,
|
1169
|
+
negative_prompt_embeds,
|
1170
|
+
pooled_prompt_embeds,
|
1171
|
+
ip_adapter_image,
|
1172
|
+
ip_adapter_image_embeds,
|
1173
|
+
negative_pooled_prompt_embeds,
|
1174
|
+
controlnet_conditioning_scale,
|
1175
|
+
control_guidance_start,
|
1176
|
+
control_guidance_end,
|
1177
|
+
callback_on_step_end_tensor_inputs,
|
1178
|
+
)
|
1179
|
+
|
1180
|
+
control_type = torch.Tensor(control_type)
|
1181
|
+
|
1182
|
+
self._guidance_scale = guidance_scale
|
1183
|
+
self._clip_skip = clip_skip
|
1184
|
+
self._cross_attention_kwargs = cross_attention_kwargs
|
1185
|
+
self._denoising_end = denoising_end
|
1186
|
+
self._interrupt = False
|
1187
|
+
|
1188
|
+
# 2. Define call parameters
|
1189
|
+
if prompt is not None and isinstance(prompt, str):
|
1190
|
+
batch_size = 1
|
1191
|
+
elif prompt is not None and isinstance(prompt, list):
|
1192
|
+
batch_size = len(prompt)
|
1193
|
+
else:
|
1194
|
+
batch_size = prompt_embeds.shape[0]
|
1195
|
+
|
1196
|
+
device = self._execution_device
|
1197
|
+
|
1198
|
+
global_pool_conditions = controlnet.config.global_pool_conditions
|
1199
|
+
guess_mode = guess_mode or global_pool_conditions
|
1200
|
+
|
1201
|
+
# 3.1 Encode input prompt
|
1202
|
+
text_encoder_lora_scale = (
|
1203
|
+
self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
|
1204
|
+
)
|
1205
|
+
(
|
1206
|
+
prompt_embeds,
|
1207
|
+
negative_prompt_embeds,
|
1208
|
+
pooled_prompt_embeds,
|
1209
|
+
negative_pooled_prompt_embeds,
|
1210
|
+
) = self.encode_prompt(
|
1211
|
+
prompt,
|
1212
|
+
prompt_2,
|
1213
|
+
device,
|
1214
|
+
num_images_per_prompt,
|
1215
|
+
self.do_classifier_free_guidance,
|
1216
|
+
negative_prompt,
|
1217
|
+
negative_prompt_2,
|
1218
|
+
prompt_embeds=prompt_embeds,
|
1219
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
1220
|
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
1221
|
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
1222
|
+
lora_scale=text_encoder_lora_scale,
|
1223
|
+
clip_skip=self.clip_skip,
|
1224
|
+
)
|
1225
|
+
|
1226
|
+
# 3.2 Encode ip_adapter_image
|
1227
|
+
if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
|
1228
|
+
image_embeds = self.prepare_ip_adapter_image_embeds(
|
1229
|
+
ip_adapter_image,
|
1230
|
+
ip_adapter_image_embeds,
|
1231
|
+
device,
|
1232
|
+
batch_size * num_images_per_prompt,
|
1233
|
+
self.do_classifier_free_guidance,
|
1234
|
+
)
|
1235
|
+
|
1236
|
+
# 4. Prepare image
|
1237
|
+
for idx, _ in enumerate(control_image):
|
1238
|
+
control_image[idx] = self.prepare_image(
|
1239
|
+
image=control_image[idx],
|
1240
|
+
width=width,
|
1241
|
+
height=height,
|
1242
|
+
batch_size=batch_size * num_images_per_prompt,
|
1243
|
+
num_images_per_prompt=num_images_per_prompt,
|
1244
|
+
device=device,
|
1245
|
+
dtype=controlnet.dtype,
|
1246
|
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
1247
|
+
guess_mode=guess_mode,
|
1248
|
+
)
|
1249
|
+
height, width = control_image[idx].shape[-2:]
|
1250
|
+
|
1251
|
+
# 5. Prepare timesteps
|
1252
|
+
timesteps, num_inference_steps = retrieve_timesteps(
|
1253
|
+
self.scheduler, num_inference_steps, device, timesteps, sigmas
|
1254
|
+
)
|
1255
|
+
self._num_timesteps = len(timesteps)
|
1256
|
+
|
1257
|
+
# 6. Prepare latent variables
|
1258
|
+
num_channels_latents = self.unet.config.in_channels
|
1259
|
+
latents = self.prepare_latents(
|
1260
|
+
batch_size * num_images_per_prompt,
|
1261
|
+
num_channels_latents,
|
1262
|
+
height,
|
1263
|
+
width,
|
1264
|
+
prompt_embeds.dtype,
|
1265
|
+
device,
|
1266
|
+
generator,
|
1267
|
+
latents,
|
1268
|
+
)
|
1269
|
+
|
1270
|
+
# 6.5 Optionally get Guidance Scale Embedding
|
1271
|
+
timestep_cond = None
|
1272
|
+
if self.unet.config.time_cond_proj_dim is not None:
|
1273
|
+
guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
|
1274
|
+
timestep_cond = self.get_guidance_scale_embedding(
|
1275
|
+
guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
|
1276
|
+
).to(device=device, dtype=latents.dtype)
|
1277
|
+
|
1278
|
+
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
1279
|
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
1280
|
+
|
1281
|
+
# 7.1 Create tensor stating which controlnets to keep
|
1282
|
+
controlnet_keep = []
|
1283
|
+
for i in range(len(timesteps)):
|
1284
|
+
controlnet_keep.append(
|
1285
|
+
1.0
|
1286
|
+
- float(i / len(timesteps) < control_guidance_start or (i + 1) / len(timesteps) > control_guidance_end)
|
1287
|
+
)
|
1288
|
+
|
1289
|
+
# 7.2 Prepare added time ids & embeddings
|
1290
|
+
original_size = original_size or (height, width)
|
1291
|
+
target_size = target_size or (height, width)
|
1292
|
+
for _image in control_image:
|
1293
|
+
if isinstance(_image, torch.Tensor):
|
1294
|
+
original_size = original_size or _image.shape[-2:]
|
1295
|
+
add_text_embeds = pooled_prompt_embeds
|
1296
|
+
if self.text_encoder_2 is None:
|
1297
|
+
text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
|
1298
|
+
else:
|
1299
|
+
text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
|
1300
|
+
|
1301
|
+
add_time_ids = self._get_add_time_ids(
|
1302
|
+
original_size,
|
1303
|
+
crops_coords_top_left,
|
1304
|
+
target_size,
|
1305
|
+
dtype=prompt_embeds.dtype,
|
1306
|
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
1307
|
+
)
|
1308
|
+
|
1309
|
+
if negative_original_size is not None and negative_target_size is not None:
|
1310
|
+
negative_add_time_ids = self._get_add_time_ids(
|
1311
|
+
negative_original_size,
|
1312
|
+
negative_crops_coords_top_left,
|
1313
|
+
negative_target_size,
|
1314
|
+
dtype=prompt_embeds.dtype,
|
1315
|
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
1316
|
+
)
|
1317
|
+
else:
|
1318
|
+
negative_add_time_ids = add_time_ids
|
1319
|
+
|
1320
|
+
if self.do_classifier_free_guidance:
|
1321
|
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
1322
|
+
add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
|
1323
|
+
add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
|
1324
|
+
|
1325
|
+
prompt_embeds = prompt_embeds.to(device)
|
1326
|
+
add_text_embeds = add_text_embeds.to(device)
|
1327
|
+
add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
|
1328
|
+
|
1329
|
+
# 8. Denoising loop
|
1330
|
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
1331
|
+
|
1332
|
+
# 8.1 Apply denoising_end
|
1333
|
+
if (
|
1334
|
+
self.denoising_end is not None
|
1335
|
+
and isinstance(self.denoising_end, float)
|
1336
|
+
and self.denoising_end > 0
|
1337
|
+
and self.denoising_end < 1
|
1338
|
+
):
|
1339
|
+
discrete_timestep_cutoff = int(
|
1340
|
+
round(
|
1341
|
+
self.scheduler.config.num_train_timesteps
|
1342
|
+
- (self.denoising_end * self.scheduler.config.num_train_timesteps)
|
1343
|
+
)
|
1344
|
+
)
|
1345
|
+
num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
|
1346
|
+
timesteps = timesteps[:num_inference_steps]
|
1347
|
+
|
1348
|
+
is_unet_compiled = is_compiled_module(self.unet)
|
1349
|
+
is_controlnet_compiled = is_compiled_module(self.controlnet)
|
1350
|
+
is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
|
1351
|
+
|
1352
|
+
control_type = (
|
1353
|
+
control_type.reshape(1, -1)
|
1354
|
+
.to(device, dtype=prompt_embeds.dtype)
|
1355
|
+
.repeat(batch_size * num_images_per_prompt * 2, 1)
|
1356
|
+
)
|
1357
|
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
1358
|
+
for i, t in enumerate(timesteps):
|
1359
|
+
if self.interrupt:
|
1360
|
+
continue
|
1361
|
+
|
1362
|
+
# Relevant thread:
|
1363
|
+
# https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
|
1364
|
+
if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1:
|
1365
|
+
torch._inductor.cudagraph_mark_step_begin()
|
1366
|
+
# expand the latents if we are doing classifier free guidance
|
1367
|
+
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
1368
|
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
1369
|
+
|
1370
|
+
added_cond_kwargs = {
|
1371
|
+
"text_embeds": add_text_embeds,
|
1372
|
+
"time_ids": add_time_ids,
|
1373
|
+
}
|
1374
|
+
|
1375
|
+
# controlnet(s) inference
|
1376
|
+
if guess_mode and self.do_classifier_free_guidance:
|
1377
|
+
# Infer ControlNet only for the conditional batch.
|
1378
|
+
control_model_input = latents
|
1379
|
+
control_model_input = self.scheduler.scale_model_input(control_model_input, t)
|
1380
|
+
controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
|
1381
|
+
controlnet_added_cond_kwargs = {
|
1382
|
+
"text_embeds": add_text_embeds.chunk(2)[1],
|
1383
|
+
"time_ids": add_time_ids.chunk(2)[1],
|
1384
|
+
}
|
1385
|
+
else:
|
1386
|
+
control_model_input = latent_model_input
|
1387
|
+
controlnet_prompt_embeds = prompt_embeds
|
1388
|
+
controlnet_added_cond_kwargs = added_cond_kwargs
|
1389
|
+
|
1390
|
+
if isinstance(controlnet_keep[i], list):
|
1391
|
+
cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
|
1392
|
+
else:
|
1393
|
+
controlnet_cond_scale = controlnet_conditioning_scale
|
1394
|
+
if isinstance(controlnet_cond_scale, list):
|
1395
|
+
controlnet_cond_scale = controlnet_cond_scale[0]
|
1396
|
+
cond_scale = controlnet_cond_scale * controlnet_keep[i]
|
1397
|
+
|
1398
|
+
down_block_res_samples, mid_block_res_sample = self.controlnet(
|
1399
|
+
control_model_input,
|
1400
|
+
t,
|
1401
|
+
encoder_hidden_states=controlnet_prompt_embeds,
|
1402
|
+
controlnet_cond=control_image,
|
1403
|
+
control_type=control_type,
|
1404
|
+
control_type_idx=control_mode,
|
1405
|
+
conditioning_scale=cond_scale,
|
1406
|
+
guess_mode=guess_mode,
|
1407
|
+
added_cond_kwargs=controlnet_added_cond_kwargs,
|
1408
|
+
return_dict=False,
|
1409
|
+
)
|
1410
|
+
|
1411
|
+
if guess_mode and self.do_classifier_free_guidance:
|
1412
|
+
# Inferred ControlNet only for the conditional batch.
|
1413
|
+
# To apply the output of ControlNet to both the unconditional and conditional batches,
|
1414
|
+
# add 0 to the unconditional batch to keep it unchanged.
|
1415
|
+
down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
|
1416
|
+
mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
|
1417
|
+
|
1418
|
+
if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
|
1419
|
+
added_cond_kwargs["image_embeds"] = image_embeds
|
1420
|
+
|
1421
|
+
# predict the noise residual
|
1422
|
+
noise_pred = self.unet(
|
1423
|
+
latent_model_input,
|
1424
|
+
t,
|
1425
|
+
encoder_hidden_states=prompt_embeds,
|
1426
|
+
timestep_cond=timestep_cond,
|
1427
|
+
cross_attention_kwargs=self.cross_attention_kwargs,
|
1428
|
+
down_block_additional_residuals=down_block_res_samples,
|
1429
|
+
mid_block_additional_residual=mid_block_res_sample,
|
1430
|
+
added_cond_kwargs=added_cond_kwargs,
|
1431
|
+
return_dict=False,
|
1432
|
+
)[0]
|
1433
|
+
|
1434
|
+
# perform guidance
|
1435
|
+
if self.do_classifier_free_guidance:
|
1436
|
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
1437
|
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
1438
|
+
|
1439
|
+
# compute the previous noisy sample x_t -> x_t-1
|
1440
|
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
1441
|
+
|
1442
|
+
if callback_on_step_end is not None:
|
1443
|
+
callback_kwargs = {}
|
1444
|
+
for k in callback_on_step_end_tensor_inputs:
|
1445
|
+
callback_kwargs[k] = locals()[k]
|
1446
|
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
1447
|
+
|
1448
|
+
latents = callback_outputs.pop("latents", latents)
|
1449
|
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
1450
|
+
add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
|
1451
|
+
add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
|
1452
|
+
|
1453
|
+
# call the callback, if provided
|
1454
|
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
1455
|
+
progress_bar.update()
|
1456
|
+
|
1457
|
+
if not output_type == "latent":
|
1458
|
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
1459
|
+
needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
|
1460
|
+
|
1461
|
+
if needs_upcasting:
|
1462
|
+
self.upcast_vae()
|
1463
|
+
latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
1464
|
+
|
1465
|
+
# unscale/denormalize the latents
|
1466
|
+
# denormalize with the mean and std if available and not None
|
1467
|
+
has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
|
1468
|
+
has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
|
1469
|
+
if has_latents_mean and has_latents_std:
|
1470
|
+
latents_mean = (
|
1471
|
+
torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
|
1472
|
+
)
|
1473
|
+
latents_std = (
|
1474
|
+
torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
|
1475
|
+
)
|
1476
|
+
latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
|
1477
|
+
else:
|
1478
|
+
latents = latents / self.vae.config.scaling_factor
|
1479
|
+
|
1480
|
+
image = self.vae.decode(latents, return_dict=False)[0]
|
1481
|
+
|
1482
|
+
# cast back to fp16 if needed
|
1483
|
+
if needs_upcasting:
|
1484
|
+
self.vae.to(dtype=torch.float16)
|
1485
|
+
else:
|
1486
|
+
image = latents
|
1487
|
+
|
1488
|
+
if not output_type == "latent":
|
1489
|
+
# apply watermark if available
|
1490
|
+
if self.watermark is not None:
|
1491
|
+
image = self.watermark.apply_watermark(image)
|
1492
|
+
|
1493
|
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
1494
|
+
|
1495
|
+
# Offload all models
|
1496
|
+
self.maybe_free_model_hooks()
|
1497
|
+
|
1498
|
+
if not return_dict:
|
1499
|
+
return (image,)
|
1500
|
+
|
1501
|
+
return StableDiffusionXLPipelineOutput(images=image)
|