diffusers 0.27.0__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 +50 -53
- 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.0.dist-info → diffusers-0.32.2.dist-info}/METADATA +82 -91
- diffusers-0.32.2.dist-info/RECORD +550 -0
- {diffusers-0.27.0.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.0.dist-info/RECORD +0 -399
- {diffusers-0.27.0.dist-info → diffusers-0.32.2.dist-info}/LICENSE +0 -0
- {diffusers-0.27.0.dist-info → diffusers-0.32.2.dist-info}/entry_points.txt +0 -0
- {diffusers-0.27.0.dist-info → diffusers-0.32.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,916 @@
|
|
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
|
+
import inspect
|
16
|
+
from typing import Any, Callable, Dict, List, Optional, Union
|
17
|
+
|
18
|
+
import numpy as np
|
19
|
+
import PIL.Image
|
20
|
+
import torch
|
21
|
+
import torch.nn.functional as F
|
22
|
+
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
|
23
|
+
|
24
|
+
from ...callbacks import MultiPipelineCallbacks, PipelineCallback
|
25
|
+
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
26
|
+
from ...loaders import FromSingleFileMixin, StableDiffusionLoraLoaderMixin, TextualInversionLoaderMixin
|
27
|
+
from ...models import AutoencoderKL, ControlNetXSAdapter, UNet2DConditionModel, UNetControlNetXSModel
|
28
|
+
from ...models.lora import adjust_lora_scale_text_encoder
|
29
|
+
from ...schedulers import KarrasDiffusionSchedulers
|
30
|
+
from ...utils import (
|
31
|
+
USE_PEFT_BACKEND,
|
32
|
+
deprecate,
|
33
|
+
logging,
|
34
|
+
replace_example_docstring,
|
35
|
+
scale_lora_layers,
|
36
|
+
unscale_lora_layers,
|
37
|
+
)
|
38
|
+
from ...utils.torch_utils import is_compiled_module, is_torch_version, randn_tensor
|
39
|
+
from ..pipeline_utils import DiffusionPipeline, StableDiffusionMixin
|
40
|
+
from ..stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
|
41
|
+
from ..stable_diffusion.safety_checker import StableDiffusionSafetyChecker
|
42
|
+
|
43
|
+
|
44
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
45
|
+
|
46
|
+
|
47
|
+
EXAMPLE_DOC_STRING = """
|
48
|
+
Examples:
|
49
|
+
```py
|
50
|
+
>>> # !pip install opencv-python transformers accelerate
|
51
|
+
>>> from diffusers import StableDiffusionControlNetXSPipeline, ControlNetXSAdapter
|
52
|
+
>>> from diffusers.utils import load_image
|
53
|
+
>>> import numpy as np
|
54
|
+
>>> import torch
|
55
|
+
|
56
|
+
>>> import cv2
|
57
|
+
>>> from PIL import Image
|
58
|
+
|
59
|
+
>>> prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
|
60
|
+
>>> negative_prompt = "low quality, bad quality, sketches"
|
61
|
+
|
62
|
+
>>> # download an image
|
63
|
+
>>> image = load_image(
|
64
|
+
... "https://hf.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
|
65
|
+
... )
|
66
|
+
|
67
|
+
>>> # initialize the models and pipeline
|
68
|
+
>>> controlnet_conditioning_scale = 0.5
|
69
|
+
|
70
|
+
>>> controlnet = ControlNetXSAdapter.from_pretrained(
|
71
|
+
... "UmerHA/Testing-ConrolNetXS-SD2.1-canny", torch_dtype=torch.float16
|
72
|
+
... )
|
73
|
+
>>> pipe = StableDiffusionControlNetXSPipeline.from_pretrained(
|
74
|
+
... "stabilityai/stable-diffusion-2-1-base", controlnet=controlnet, torch_dtype=torch.float16
|
75
|
+
... )
|
76
|
+
>>> pipe.enable_model_cpu_offload()
|
77
|
+
|
78
|
+
>>> # get canny image
|
79
|
+
>>> image = np.array(image)
|
80
|
+
>>> image = cv2.Canny(image, 100, 200)
|
81
|
+
>>> image = image[:, :, None]
|
82
|
+
>>> image = np.concatenate([image, image, image], axis=2)
|
83
|
+
>>> canny_image = Image.fromarray(image)
|
84
|
+
>>> # generate image
|
85
|
+
>>> image = pipe(
|
86
|
+
... prompt, controlnet_conditioning_scale=controlnet_conditioning_scale, image=canny_image
|
87
|
+
... ).images[0]
|
88
|
+
```
|
89
|
+
"""
|
90
|
+
|
91
|
+
|
92
|
+
class StableDiffusionControlNetXSPipeline(
|
93
|
+
DiffusionPipeline,
|
94
|
+
StableDiffusionMixin,
|
95
|
+
TextualInversionLoaderMixin,
|
96
|
+
StableDiffusionLoraLoaderMixin,
|
97
|
+
FromSingleFileMixin,
|
98
|
+
):
|
99
|
+
r"""
|
100
|
+
Pipeline for text-to-image generation using Stable Diffusion with ControlNet-XS guidance.
|
101
|
+
|
102
|
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
103
|
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
104
|
+
|
105
|
+
The pipeline also inherits the following loading methods:
|
106
|
+
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
107
|
+
- [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
108
|
+
- [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
109
|
+
- [`loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
|
110
|
+
|
111
|
+
Args:
|
112
|
+
vae ([`AutoencoderKL`]):
|
113
|
+
Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
|
114
|
+
text_encoder ([`~transformers.CLIPTextModel`]):
|
115
|
+
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
116
|
+
tokenizer ([`~transformers.CLIPTokenizer`]):
|
117
|
+
A `CLIPTokenizer` to tokenize text.
|
118
|
+
unet ([`UNet2DConditionModel`]):
|
119
|
+
A [`UNet2DConditionModel`] used to create a UNetControlNetXSModel to denoise the encoded image latents.
|
120
|
+
controlnet ([`ControlNetXSAdapter`]):
|
121
|
+
A [`ControlNetXSAdapter`] to be used in combination with `unet` to denoise the encoded image latents.
|
122
|
+
scheduler ([`SchedulerMixin`]):
|
123
|
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
124
|
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
125
|
+
safety_checker ([`StableDiffusionSafetyChecker`]):
|
126
|
+
Classification module that estimates whether generated images could be considered offensive or harmful.
|
127
|
+
Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
|
128
|
+
about a model's potential harms.
|
129
|
+
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
130
|
+
A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
|
131
|
+
"""
|
132
|
+
|
133
|
+
model_cpu_offload_seq = "text_encoder->unet->vae"
|
134
|
+
_optional_components = ["safety_checker", "feature_extractor"]
|
135
|
+
_exclude_from_cpu_offload = ["safety_checker"]
|
136
|
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
137
|
+
|
138
|
+
def __init__(
|
139
|
+
self,
|
140
|
+
vae: AutoencoderKL,
|
141
|
+
text_encoder: CLIPTextModel,
|
142
|
+
tokenizer: CLIPTokenizer,
|
143
|
+
unet: Union[UNet2DConditionModel, UNetControlNetXSModel],
|
144
|
+
controlnet: ControlNetXSAdapter,
|
145
|
+
scheduler: KarrasDiffusionSchedulers,
|
146
|
+
safety_checker: StableDiffusionSafetyChecker,
|
147
|
+
feature_extractor: CLIPImageProcessor,
|
148
|
+
requires_safety_checker: bool = True,
|
149
|
+
):
|
150
|
+
super().__init__()
|
151
|
+
|
152
|
+
if isinstance(unet, UNet2DConditionModel):
|
153
|
+
unet = UNetControlNetXSModel.from_unet(unet, controlnet)
|
154
|
+
|
155
|
+
if safety_checker is None and requires_safety_checker:
|
156
|
+
logger.warning(
|
157
|
+
f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
|
158
|
+
" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
|
159
|
+
" results in services or applications open to the public. Both the diffusers team and Hugging Face"
|
160
|
+
" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
|
161
|
+
" it only for use-cases that involve analyzing network behavior or auditing its results. For more"
|
162
|
+
" information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
|
163
|
+
)
|
164
|
+
|
165
|
+
if safety_checker is not None and feature_extractor is None:
|
166
|
+
raise ValueError(
|
167
|
+
"Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
|
168
|
+
" checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
|
169
|
+
)
|
170
|
+
|
171
|
+
self.register_modules(
|
172
|
+
vae=vae,
|
173
|
+
text_encoder=text_encoder,
|
174
|
+
tokenizer=tokenizer,
|
175
|
+
unet=unet,
|
176
|
+
controlnet=controlnet,
|
177
|
+
scheduler=scheduler,
|
178
|
+
safety_checker=safety_checker,
|
179
|
+
feature_extractor=feature_extractor,
|
180
|
+
)
|
181
|
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
182
|
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
|
183
|
+
self.control_image_processor = VaeImageProcessor(
|
184
|
+
vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
|
185
|
+
)
|
186
|
+
self.register_to_config(requires_safety_checker=requires_safety_checker)
|
187
|
+
|
188
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
|
189
|
+
def _encode_prompt(
|
190
|
+
self,
|
191
|
+
prompt,
|
192
|
+
device,
|
193
|
+
num_images_per_prompt,
|
194
|
+
do_classifier_free_guidance,
|
195
|
+
negative_prompt=None,
|
196
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
197
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
198
|
+
lora_scale: Optional[float] = None,
|
199
|
+
**kwargs,
|
200
|
+
):
|
201
|
+
deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
|
202
|
+
deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
|
203
|
+
|
204
|
+
prompt_embeds_tuple = self.encode_prompt(
|
205
|
+
prompt=prompt,
|
206
|
+
device=device,
|
207
|
+
num_images_per_prompt=num_images_per_prompt,
|
208
|
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
209
|
+
negative_prompt=negative_prompt,
|
210
|
+
prompt_embeds=prompt_embeds,
|
211
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
212
|
+
lora_scale=lora_scale,
|
213
|
+
**kwargs,
|
214
|
+
)
|
215
|
+
|
216
|
+
# concatenate for backwards comp
|
217
|
+
prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
|
218
|
+
|
219
|
+
return prompt_embeds
|
220
|
+
|
221
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt
|
222
|
+
def encode_prompt(
|
223
|
+
self,
|
224
|
+
prompt,
|
225
|
+
device,
|
226
|
+
num_images_per_prompt,
|
227
|
+
do_classifier_free_guidance,
|
228
|
+
negative_prompt=None,
|
229
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
230
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
231
|
+
lora_scale: Optional[float] = None,
|
232
|
+
clip_skip: Optional[int] = None,
|
233
|
+
):
|
234
|
+
r"""
|
235
|
+
Encodes the prompt into text encoder hidden states.
|
236
|
+
|
237
|
+
Args:
|
238
|
+
prompt (`str` or `List[str]`, *optional*):
|
239
|
+
prompt to be encoded
|
240
|
+
device: (`torch.device`):
|
241
|
+
torch device
|
242
|
+
num_images_per_prompt (`int`):
|
243
|
+
number of images that should be generated per prompt
|
244
|
+
do_classifier_free_guidance (`bool`):
|
245
|
+
whether to use classifier free guidance or not
|
246
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
247
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
248
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
249
|
+
less than `1`).
|
250
|
+
prompt_embeds (`torch.Tensor`, *optional*):
|
251
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
252
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
253
|
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
254
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
255
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
256
|
+
argument.
|
257
|
+
lora_scale (`float`, *optional*):
|
258
|
+
A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
259
|
+
clip_skip (`int`, *optional*):
|
260
|
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
261
|
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
262
|
+
"""
|
263
|
+
# set lora scale so that monkey patched LoRA
|
264
|
+
# function of text encoder can correctly access it
|
265
|
+
if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
|
266
|
+
self._lora_scale = lora_scale
|
267
|
+
|
268
|
+
# dynamically adjust the LoRA scale
|
269
|
+
if not USE_PEFT_BACKEND:
|
270
|
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
271
|
+
else:
|
272
|
+
scale_lora_layers(self.text_encoder, lora_scale)
|
273
|
+
|
274
|
+
if prompt is not None and isinstance(prompt, str):
|
275
|
+
batch_size = 1
|
276
|
+
elif prompt is not None and isinstance(prompt, list):
|
277
|
+
batch_size = len(prompt)
|
278
|
+
else:
|
279
|
+
batch_size = prompt_embeds.shape[0]
|
280
|
+
|
281
|
+
if prompt_embeds is None:
|
282
|
+
# textual inversion: process multi-vector tokens if necessary
|
283
|
+
if isinstance(self, TextualInversionLoaderMixin):
|
284
|
+
prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
|
285
|
+
|
286
|
+
text_inputs = self.tokenizer(
|
287
|
+
prompt,
|
288
|
+
padding="max_length",
|
289
|
+
max_length=self.tokenizer.model_max_length,
|
290
|
+
truncation=True,
|
291
|
+
return_tensors="pt",
|
292
|
+
)
|
293
|
+
text_input_ids = text_inputs.input_ids
|
294
|
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
295
|
+
|
296
|
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
297
|
+
text_input_ids, untruncated_ids
|
298
|
+
):
|
299
|
+
removed_text = self.tokenizer.batch_decode(
|
300
|
+
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
|
301
|
+
)
|
302
|
+
logger.warning(
|
303
|
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
304
|
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
305
|
+
)
|
306
|
+
|
307
|
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
308
|
+
attention_mask = text_inputs.attention_mask.to(device)
|
309
|
+
else:
|
310
|
+
attention_mask = None
|
311
|
+
|
312
|
+
if clip_skip is None:
|
313
|
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
|
314
|
+
prompt_embeds = prompt_embeds[0]
|
315
|
+
else:
|
316
|
+
prompt_embeds = self.text_encoder(
|
317
|
+
text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
|
318
|
+
)
|
319
|
+
# Access the `hidden_states` first, that contains a tuple of
|
320
|
+
# all the hidden states from the encoder layers. Then index into
|
321
|
+
# the tuple to access the hidden states from the desired layer.
|
322
|
+
prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
|
323
|
+
# We also need to apply the final LayerNorm here to not mess with the
|
324
|
+
# representations. The `last_hidden_states` that we typically use for
|
325
|
+
# obtaining the final prompt representations passes through the LayerNorm
|
326
|
+
# layer.
|
327
|
+
prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
|
328
|
+
|
329
|
+
if self.text_encoder is not None:
|
330
|
+
prompt_embeds_dtype = self.text_encoder.dtype
|
331
|
+
elif self.unet is not None:
|
332
|
+
prompt_embeds_dtype = self.unet.dtype
|
333
|
+
else:
|
334
|
+
prompt_embeds_dtype = prompt_embeds.dtype
|
335
|
+
|
336
|
+
prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
337
|
+
|
338
|
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
339
|
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
340
|
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
341
|
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
342
|
+
|
343
|
+
# get unconditional embeddings for classifier free guidance
|
344
|
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
345
|
+
uncond_tokens: List[str]
|
346
|
+
if negative_prompt is None:
|
347
|
+
uncond_tokens = [""] * batch_size
|
348
|
+
elif prompt is not None and type(prompt) is not type(negative_prompt):
|
349
|
+
raise TypeError(
|
350
|
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
351
|
+
f" {type(prompt)}."
|
352
|
+
)
|
353
|
+
elif isinstance(negative_prompt, str):
|
354
|
+
uncond_tokens = [negative_prompt]
|
355
|
+
elif batch_size != len(negative_prompt):
|
356
|
+
raise ValueError(
|
357
|
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
358
|
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
359
|
+
" the batch size of `prompt`."
|
360
|
+
)
|
361
|
+
else:
|
362
|
+
uncond_tokens = negative_prompt
|
363
|
+
|
364
|
+
# textual inversion: process multi-vector tokens if necessary
|
365
|
+
if isinstance(self, TextualInversionLoaderMixin):
|
366
|
+
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
|
367
|
+
|
368
|
+
max_length = prompt_embeds.shape[1]
|
369
|
+
uncond_input = self.tokenizer(
|
370
|
+
uncond_tokens,
|
371
|
+
padding="max_length",
|
372
|
+
max_length=max_length,
|
373
|
+
truncation=True,
|
374
|
+
return_tensors="pt",
|
375
|
+
)
|
376
|
+
|
377
|
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
378
|
+
attention_mask = uncond_input.attention_mask.to(device)
|
379
|
+
else:
|
380
|
+
attention_mask = None
|
381
|
+
|
382
|
+
negative_prompt_embeds = self.text_encoder(
|
383
|
+
uncond_input.input_ids.to(device),
|
384
|
+
attention_mask=attention_mask,
|
385
|
+
)
|
386
|
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
387
|
+
|
388
|
+
if do_classifier_free_guidance:
|
389
|
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
390
|
+
seq_len = negative_prompt_embeds.shape[1]
|
391
|
+
|
392
|
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
393
|
+
|
394
|
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
395
|
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
396
|
+
|
397
|
+
if self.text_encoder is not None:
|
398
|
+
if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
|
399
|
+
# Retrieve the original scale by scaling back the LoRA layers
|
400
|
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
401
|
+
|
402
|
+
return prompt_embeds, negative_prompt_embeds
|
403
|
+
|
404
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
|
405
|
+
def run_safety_checker(self, image, device, dtype):
|
406
|
+
if self.safety_checker is None:
|
407
|
+
has_nsfw_concept = None
|
408
|
+
else:
|
409
|
+
if torch.is_tensor(image):
|
410
|
+
feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
|
411
|
+
else:
|
412
|
+
feature_extractor_input = self.image_processor.numpy_to_pil(image)
|
413
|
+
safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
|
414
|
+
image, has_nsfw_concept = self.safety_checker(
|
415
|
+
images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
|
416
|
+
)
|
417
|
+
return image, has_nsfw_concept
|
418
|
+
|
419
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
|
420
|
+
def decode_latents(self, latents):
|
421
|
+
deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
|
422
|
+
deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
|
423
|
+
|
424
|
+
latents = 1 / self.vae.config.scaling_factor * latents
|
425
|
+
image = self.vae.decode(latents, return_dict=False)[0]
|
426
|
+
image = (image / 2 + 0.5).clamp(0, 1)
|
427
|
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
428
|
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
429
|
+
return image
|
430
|
+
|
431
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
432
|
+
def prepare_extra_step_kwargs(self, generator, eta):
|
433
|
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
434
|
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
435
|
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
436
|
+
# and should be between [0, 1]
|
437
|
+
|
438
|
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
439
|
+
extra_step_kwargs = {}
|
440
|
+
if accepts_eta:
|
441
|
+
extra_step_kwargs["eta"] = eta
|
442
|
+
|
443
|
+
# check if the scheduler accepts generator
|
444
|
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
445
|
+
if accepts_generator:
|
446
|
+
extra_step_kwargs["generator"] = generator
|
447
|
+
return extra_step_kwargs
|
448
|
+
|
449
|
+
def check_inputs(
|
450
|
+
self,
|
451
|
+
prompt,
|
452
|
+
image,
|
453
|
+
negative_prompt=None,
|
454
|
+
prompt_embeds=None,
|
455
|
+
negative_prompt_embeds=None,
|
456
|
+
controlnet_conditioning_scale=1.0,
|
457
|
+
control_guidance_start=0.0,
|
458
|
+
control_guidance_end=1.0,
|
459
|
+
callback_on_step_end_tensor_inputs=None,
|
460
|
+
):
|
461
|
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
462
|
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
463
|
+
):
|
464
|
+
raise ValueError(
|
465
|
+
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]}"
|
466
|
+
)
|
467
|
+
|
468
|
+
if prompt is not None and prompt_embeds is not None:
|
469
|
+
raise ValueError(
|
470
|
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
471
|
+
" only forward one of the two."
|
472
|
+
)
|
473
|
+
elif prompt is None and prompt_embeds is None:
|
474
|
+
raise ValueError(
|
475
|
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
476
|
+
)
|
477
|
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
478
|
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
479
|
+
|
480
|
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
481
|
+
raise ValueError(
|
482
|
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
483
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
484
|
+
)
|
485
|
+
|
486
|
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
487
|
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
488
|
+
raise ValueError(
|
489
|
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
490
|
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
491
|
+
f" {negative_prompt_embeds.shape}."
|
492
|
+
)
|
493
|
+
|
494
|
+
# Check `image` and `controlnet_conditioning_scale`
|
495
|
+
is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
|
496
|
+
self.unet, torch._dynamo.eval_frame.OptimizedModule
|
497
|
+
)
|
498
|
+
if (
|
499
|
+
isinstance(self.unet, UNetControlNetXSModel)
|
500
|
+
or is_compiled
|
501
|
+
and isinstance(self.unet._orig_mod, UNetControlNetXSModel)
|
502
|
+
):
|
503
|
+
self.check_image(image, prompt, prompt_embeds)
|
504
|
+
if not isinstance(controlnet_conditioning_scale, float):
|
505
|
+
raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
|
506
|
+
else:
|
507
|
+
assert False
|
508
|
+
|
509
|
+
start, end = control_guidance_start, control_guidance_end
|
510
|
+
if start >= end:
|
511
|
+
raise ValueError(
|
512
|
+
f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
|
513
|
+
)
|
514
|
+
if start < 0.0:
|
515
|
+
raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
|
516
|
+
if end > 1.0:
|
517
|
+
raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
|
518
|
+
|
519
|
+
def check_image(self, image, prompt, prompt_embeds):
|
520
|
+
image_is_pil = isinstance(image, PIL.Image.Image)
|
521
|
+
image_is_tensor = isinstance(image, torch.Tensor)
|
522
|
+
image_is_np = isinstance(image, np.ndarray)
|
523
|
+
image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
|
524
|
+
image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
|
525
|
+
image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
|
526
|
+
|
527
|
+
if (
|
528
|
+
not image_is_pil
|
529
|
+
and not image_is_tensor
|
530
|
+
and not image_is_np
|
531
|
+
and not image_is_pil_list
|
532
|
+
and not image_is_tensor_list
|
533
|
+
and not image_is_np_list
|
534
|
+
):
|
535
|
+
raise TypeError(
|
536
|
+
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)}"
|
537
|
+
)
|
538
|
+
|
539
|
+
if image_is_pil:
|
540
|
+
image_batch_size = 1
|
541
|
+
else:
|
542
|
+
image_batch_size = len(image)
|
543
|
+
|
544
|
+
if prompt is not None and isinstance(prompt, str):
|
545
|
+
prompt_batch_size = 1
|
546
|
+
elif prompt is not None and isinstance(prompt, list):
|
547
|
+
prompt_batch_size = len(prompt)
|
548
|
+
elif prompt_embeds is not None:
|
549
|
+
prompt_batch_size = prompt_embeds.shape[0]
|
550
|
+
|
551
|
+
if image_batch_size != 1 and image_batch_size != prompt_batch_size:
|
552
|
+
raise ValueError(
|
553
|
+
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}"
|
554
|
+
)
|
555
|
+
|
556
|
+
def prepare_image(
|
557
|
+
self,
|
558
|
+
image,
|
559
|
+
width,
|
560
|
+
height,
|
561
|
+
batch_size,
|
562
|
+
num_images_per_prompt,
|
563
|
+
device,
|
564
|
+
dtype,
|
565
|
+
do_classifier_free_guidance=False,
|
566
|
+
):
|
567
|
+
image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
|
568
|
+
image_batch_size = image.shape[0]
|
569
|
+
|
570
|
+
if image_batch_size == 1:
|
571
|
+
repeat_by = batch_size
|
572
|
+
else:
|
573
|
+
# image batch size is the same as prompt batch size
|
574
|
+
repeat_by = num_images_per_prompt
|
575
|
+
|
576
|
+
image = image.repeat_interleave(repeat_by, dim=0)
|
577
|
+
|
578
|
+
image = image.to(device=device, dtype=dtype)
|
579
|
+
|
580
|
+
if do_classifier_free_guidance:
|
581
|
+
image = torch.cat([image] * 2)
|
582
|
+
|
583
|
+
return image
|
584
|
+
|
585
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
|
586
|
+
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
|
587
|
+
shape = (
|
588
|
+
batch_size,
|
589
|
+
num_channels_latents,
|
590
|
+
int(height) // self.vae_scale_factor,
|
591
|
+
int(width) // self.vae_scale_factor,
|
592
|
+
)
|
593
|
+
if isinstance(generator, list) and len(generator) != batch_size:
|
594
|
+
raise ValueError(
|
595
|
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
596
|
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
597
|
+
)
|
598
|
+
|
599
|
+
if latents is None:
|
600
|
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
601
|
+
else:
|
602
|
+
latents = latents.to(device)
|
603
|
+
|
604
|
+
# scale the initial noise by the standard deviation required by the scheduler
|
605
|
+
latents = latents * self.scheduler.init_noise_sigma
|
606
|
+
return latents
|
607
|
+
|
608
|
+
@property
|
609
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.guidance_scale
|
610
|
+
def guidance_scale(self):
|
611
|
+
return self._guidance_scale
|
612
|
+
|
613
|
+
@property
|
614
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.clip_skip
|
615
|
+
def clip_skip(self):
|
616
|
+
return self._clip_skip
|
617
|
+
|
618
|
+
@property
|
619
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.do_classifier_free_guidance
|
620
|
+
def do_classifier_free_guidance(self):
|
621
|
+
return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
|
622
|
+
|
623
|
+
@property
|
624
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.cross_attention_kwargs
|
625
|
+
def cross_attention_kwargs(self):
|
626
|
+
return self._cross_attention_kwargs
|
627
|
+
|
628
|
+
@property
|
629
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.num_timesteps
|
630
|
+
def num_timesteps(self):
|
631
|
+
return self._num_timesteps
|
632
|
+
|
633
|
+
@torch.no_grad()
|
634
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
635
|
+
def __call__(
|
636
|
+
self,
|
637
|
+
prompt: Union[str, List[str]] = None,
|
638
|
+
image: PipelineImageInput = None,
|
639
|
+
height: Optional[int] = None,
|
640
|
+
width: Optional[int] = None,
|
641
|
+
num_inference_steps: int = 50,
|
642
|
+
guidance_scale: float = 7.5,
|
643
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
644
|
+
num_images_per_prompt: Optional[int] = 1,
|
645
|
+
eta: float = 0.0,
|
646
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
647
|
+
latents: Optional[torch.Tensor] = None,
|
648
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
649
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
650
|
+
output_type: Optional[str] = "pil",
|
651
|
+
return_dict: bool = True,
|
652
|
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
653
|
+
controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
|
654
|
+
control_guidance_start: float = 0.0,
|
655
|
+
control_guidance_end: float = 1.0,
|
656
|
+
clip_skip: Optional[int] = None,
|
657
|
+
callback_on_step_end: Optional[
|
658
|
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
659
|
+
] = None,
|
660
|
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
661
|
+
):
|
662
|
+
r"""
|
663
|
+
The call function to the pipeline for generation.
|
664
|
+
|
665
|
+
Args:
|
666
|
+
prompt (`str` or `List[str]`, *optional*):
|
667
|
+
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
668
|
+
image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
|
669
|
+
`List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
|
670
|
+
The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
|
671
|
+
specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted
|
672
|
+
as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or
|
673
|
+
width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`,
|
674
|
+
images must be passed as a list such that each element of the list can be correctly batched for input
|
675
|
+
to a single ControlNet.
|
676
|
+
height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
677
|
+
The height in pixels of the generated image.
|
678
|
+
width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
679
|
+
The width in pixels of the generated image.
|
680
|
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
681
|
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
682
|
+
expense of slower inference.
|
683
|
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
684
|
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
685
|
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
686
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
687
|
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
688
|
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
689
|
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
690
|
+
The number of images to generate per prompt.
|
691
|
+
eta (`float`, *optional*, defaults to 0.0):
|
692
|
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
693
|
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
694
|
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
695
|
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
696
|
+
generation deterministic.
|
697
|
+
latents (`torch.Tensor`, *optional*):
|
698
|
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
699
|
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
700
|
+
tensor is generated by sampling using the supplied random `generator`.
|
701
|
+
prompt_embeds (`torch.Tensor`, *optional*):
|
702
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
703
|
+
provided, text embeddings are generated from the `prompt` input argument.
|
704
|
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
705
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
706
|
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
707
|
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
708
|
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
709
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
710
|
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
711
|
+
plain tuple.
|
712
|
+
cross_attention_kwargs (`dict`, *optional*):
|
713
|
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
714
|
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
715
|
+
controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
|
716
|
+
The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
|
717
|
+
to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
|
718
|
+
the corresponding scale as a list.
|
719
|
+
control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
|
720
|
+
The percentage of total steps at which the ControlNet starts applying.
|
721
|
+
control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
|
722
|
+
The percentage of total steps at which the ControlNet stops applying.
|
723
|
+
clip_skip (`int`, *optional*):
|
724
|
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
725
|
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
726
|
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
727
|
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
728
|
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
729
|
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
730
|
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
731
|
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
732
|
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
733
|
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
734
|
+
`._callback_tensor_inputs` attribute of your pipeine class.
|
735
|
+
Examples:
|
736
|
+
|
737
|
+
Returns:
|
738
|
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
739
|
+
If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
|
740
|
+
otherwise a `tuple` is returned where the first element is a list with the generated images and the
|
741
|
+
second element is a list of `bool`s indicating whether the corresponding generated image contains
|
742
|
+
"not-safe-for-work" (nsfw) content.
|
743
|
+
"""
|
744
|
+
|
745
|
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
746
|
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
747
|
+
|
748
|
+
unet = self.unet._orig_mod if is_compiled_module(self.unet) else self.unet
|
749
|
+
|
750
|
+
# 1. Check inputs. Raise error if not correct
|
751
|
+
self.check_inputs(
|
752
|
+
prompt,
|
753
|
+
image,
|
754
|
+
negative_prompt,
|
755
|
+
prompt_embeds,
|
756
|
+
negative_prompt_embeds,
|
757
|
+
controlnet_conditioning_scale,
|
758
|
+
control_guidance_start,
|
759
|
+
control_guidance_end,
|
760
|
+
callback_on_step_end_tensor_inputs,
|
761
|
+
)
|
762
|
+
|
763
|
+
self._guidance_scale = guidance_scale
|
764
|
+
self._clip_skip = clip_skip
|
765
|
+
self._cross_attention_kwargs = cross_attention_kwargs
|
766
|
+
self._interrupt = False
|
767
|
+
|
768
|
+
# 2. Define call parameters
|
769
|
+
if prompt is not None and isinstance(prompt, str):
|
770
|
+
batch_size = 1
|
771
|
+
elif prompt is not None and isinstance(prompt, list):
|
772
|
+
batch_size = len(prompt)
|
773
|
+
else:
|
774
|
+
batch_size = prompt_embeds.shape[0]
|
775
|
+
|
776
|
+
device = self._execution_device
|
777
|
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
778
|
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
779
|
+
# corresponds to doing no classifier free guidance.
|
780
|
+
do_classifier_free_guidance = guidance_scale > 1.0
|
781
|
+
|
782
|
+
# 3. Encode input prompt
|
783
|
+
text_encoder_lora_scale = (
|
784
|
+
cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
|
785
|
+
)
|
786
|
+
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
787
|
+
prompt,
|
788
|
+
device,
|
789
|
+
num_images_per_prompt,
|
790
|
+
do_classifier_free_guidance,
|
791
|
+
negative_prompt,
|
792
|
+
prompt_embeds=prompt_embeds,
|
793
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
794
|
+
lora_scale=text_encoder_lora_scale,
|
795
|
+
clip_skip=clip_skip,
|
796
|
+
)
|
797
|
+
|
798
|
+
# For classifier free guidance, we need to do two forward passes.
|
799
|
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
800
|
+
# to avoid doing two forward passes
|
801
|
+
if do_classifier_free_guidance:
|
802
|
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
803
|
+
|
804
|
+
# 4. Prepare image
|
805
|
+
image = self.prepare_image(
|
806
|
+
image=image,
|
807
|
+
width=width,
|
808
|
+
height=height,
|
809
|
+
batch_size=batch_size * num_images_per_prompt,
|
810
|
+
num_images_per_prompt=num_images_per_prompt,
|
811
|
+
device=device,
|
812
|
+
dtype=unet.dtype,
|
813
|
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
814
|
+
)
|
815
|
+
height, width = image.shape[-2:]
|
816
|
+
|
817
|
+
# 5. Prepare timesteps
|
818
|
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
819
|
+
timesteps = self.scheduler.timesteps
|
820
|
+
|
821
|
+
# 6. Prepare latent variables
|
822
|
+
num_channels_latents = self.unet.in_channels
|
823
|
+
latents = self.prepare_latents(
|
824
|
+
batch_size * num_images_per_prompt,
|
825
|
+
num_channels_latents,
|
826
|
+
height,
|
827
|
+
width,
|
828
|
+
prompt_embeds.dtype,
|
829
|
+
device,
|
830
|
+
generator,
|
831
|
+
latents,
|
832
|
+
)
|
833
|
+
|
834
|
+
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
835
|
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
836
|
+
|
837
|
+
# 8. Denoising loop
|
838
|
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
839
|
+
self._num_timesteps = len(timesteps)
|
840
|
+
is_controlnet_compiled = is_compiled_module(self.unet)
|
841
|
+
is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
|
842
|
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
843
|
+
for i, t in enumerate(timesteps):
|
844
|
+
# Relevant thread:
|
845
|
+
# https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
|
846
|
+
if is_controlnet_compiled and is_torch_higher_equal_2_1:
|
847
|
+
torch._inductor.cudagraph_mark_step_begin()
|
848
|
+
# expand the latents if we are doing classifier free guidance
|
849
|
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
850
|
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
851
|
+
|
852
|
+
# predict the noise residual
|
853
|
+
apply_control = (
|
854
|
+
i / len(timesteps) >= control_guidance_start and (i + 1) / len(timesteps) <= control_guidance_end
|
855
|
+
)
|
856
|
+
noise_pred = self.unet(
|
857
|
+
sample=latent_model_input,
|
858
|
+
timestep=t,
|
859
|
+
encoder_hidden_states=prompt_embeds,
|
860
|
+
controlnet_cond=image,
|
861
|
+
conditioning_scale=controlnet_conditioning_scale,
|
862
|
+
cross_attention_kwargs=cross_attention_kwargs,
|
863
|
+
return_dict=True,
|
864
|
+
apply_control=apply_control,
|
865
|
+
).sample
|
866
|
+
|
867
|
+
# perform guidance
|
868
|
+
if do_classifier_free_guidance:
|
869
|
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
870
|
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
871
|
+
|
872
|
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
873
|
+
|
874
|
+
if callback_on_step_end is not None:
|
875
|
+
callback_kwargs = {}
|
876
|
+
for k in callback_on_step_end_tensor_inputs:
|
877
|
+
callback_kwargs[k] = locals()[k]
|
878
|
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
879
|
+
|
880
|
+
latents = callback_outputs.pop("latents", latents)
|
881
|
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
882
|
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
883
|
+
|
884
|
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
885
|
+
progress_bar.update()
|
886
|
+
|
887
|
+
# If we do sequential model offloading, let's offload unet and controlnet
|
888
|
+
# manually for max memory savings
|
889
|
+
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
890
|
+
self.unet.to("cpu")
|
891
|
+
self.controlnet.to("cpu")
|
892
|
+
torch.cuda.empty_cache()
|
893
|
+
|
894
|
+
if not output_type == "latent":
|
895
|
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
|
896
|
+
0
|
897
|
+
]
|
898
|
+
image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
|
899
|
+
else:
|
900
|
+
image = latents
|
901
|
+
has_nsfw_concept = None
|
902
|
+
|
903
|
+
if has_nsfw_concept is None:
|
904
|
+
do_denormalize = [True] * image.shape[0]
|
905
|
+
else:
|
906
|
+
do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
|
907
|
+
|
908
|
+
image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
|
909
|
+
|
910
|
+
# Offload all models
|
911
|
+
self.maybe_free_model_hooks()
|
912
|
+
|
913
|
+
if not return_dict:
|
914
|
+
return (image, has_nsfw_concept)
|
915
|
+
|
916
|
+
return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
|