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,1094 @@
|
|
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 PIL.Image
|
19
|
+
import torch
|
20
|
+
from packaging import version
|
21
|
+
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
|
22
|
+
|
23
|
+
from ...callbacks import MultiPipelineCallbacks, PipelineCallback
|
24
|
+
from ...configuration_utils import FrozenDict
|
25
|
+
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
26
|
+
from ...loaders import FromSingleFileMixin, IPAdapterMixin, StableDiffusionLoraLoaderMixin, TextualInversionLoaderMixin
|
27
|
+
from ...models import AutoencoderKL, ImageProjection, UNet2DConditionModel
|
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 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
|
+
from .pag_utils import PAGMixin
|
43
|
+
|
44
|
+
|
45
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
46
|
+
|
47
|
+
EXAMPLE_DOC_STRING = """
|
48
|
+
Examples:
|
49
|
+
```py
|
50
|
+
>>> import torch
|
51
|
+
>>> from diffusers import AutoPipelineForImage2Image
|
52
|
+
>>> from diffusers.utils import load_image
|
53
|
+
|
54
|
+
>>> pipe = AutoPipelineForImage2Image.from_pretrained(
|
55
|
+
... "runwayml/stable-diffusion-v1-5",
|
56
|
+
... torch_dtype=torch.float16,
|
57
|
+
... enable_pag=True,
|
58
|
+
... )
|
59
|
+
>>> pipe = pipe.to("cuda")
|
60
|
+
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"
|
61
|
+
|
62
|
+
>>> init_image = load_image(url).convert("RGB")
|
63
|
+
>>> prompt = "a photo of an astronaut riding a horse on mars"
|
64
|
+
>>> image = pipe(prompt, image=init_image, pag_scale=0.3).images[0]
|
65
|
+
```
|
66
|
+
"""
|
67
|
+
|
68
|
+
|
69
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
70
|
+
def retrieve_latents(
|
71
|
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
72
|
+
):
|
73
|
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
74
|
+
return encoder_output.latent_dist.sample(generator)
|
75
|
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
76
|
+
return encoder_output.latent_dist.mode()
|
77
|
+
elif hasattr(encoder_output, "latents"):
|
78
|
+
return encoder_output.latents
|
79
|
+
else:
|
80
|
+
raise AttributeError("Could not access latents of provided encoder_output")
|
81
|
+
|
82
|
+
|
83
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
84
|
+
def retrieve_timesteps(
|
85
|
+
scheduler,
|
86
|
+
num_inference_steps: Optional[int] = None,
|
87
|
+
device: Optional[Union[str, torch.device]] = None,
|
88
|
+
timesteps: Optional[List[int]] = None,
|
89
|
+
sigmas: Optional[List[float]] = None,
|
90
|
+
**kwargs,
|
91
|
+
):
|
92
|
+
r"""
|
93
|
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
94
|
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
95
|
+
|
96
|
+
Args:
|
97
|
+
scheduler (`SchedulerMixin`):
|
98
|
+
The scheduler to get timesteps from.
|
99
|
+
num_inference_steps (`int`):
|
100
|
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
101
|
+
must be `None`.
|
102
|
+
device (`str` or `torch.device`, *optional*):
|
103
|
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
104
|
+
timesteps (`List[int]`, *optional*):
|
105
|
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
106
|
+
`num_inference_steps` and `sigmas` must be `None`.
|
107
|
+
sigmas (`List[float]`, *optional*):
|
108
|
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
109
|
+
`num_inference_steps` and `timesteps` must be `None`.
|
110
|
+
|
111
|
+
Returns:
|
112
|
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
113
|
+
second element is the number of inference steps.
|
114
|
+
"""
|
115
|
+
if timesteps is not None and sigmas is not None:
|
116
|
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
117
|
+
if timesteps is not None:
|
118
|
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
119
|
+
if not accepts_timesteps:
|
120
|
+
raise ValueError(
|
121
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
122
|
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
123
|
+
)
|
124
|
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
125
|
+
timesteps = scheduler.timesteps
|
126
|
+
num_inference_steps = len(timesteps)
|
127
|
+
elif sigmas is not None:
|
128
|
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
129
|
+
if not accept_sigmas:
|
130
|
+
raise ValueError(
|
131
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
132
|
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
133
|
+
)
|
134
|
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
135
|
+
timesteps = scheduler.timesteps
|
136
|
+
num_inference_steps = len(timesteps)
|
137
|
+
else:
|
138
|
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
139
|
+
timesteps = scheduler.timesteps
|
140
|
+
return timesteps, num_inference_steps
|
141
|
+
|
142
|
+
|
143
|
+
class StableDiffusionPAGImg2ImgPipeline(
|
144
|
+
DiffusionPipeline,
|
145
|
+
StableDiffusionMixin,
|
146
|
+
TextualInversionLoaderMixin,
|
147
|
+
IPAdapterMixin,
|
148
|
+
StableDiffusionLoraLoaderMixin,
|
149
|
+
FromSingleFileMixin,
|
150
|
+
PAGMixin,
|
151
|
+
):
|
152
|
+
r"""
|
153
|
+
Pipeline for text-guided image-to-image generation using Stable Diffusion.
|
154
|
+
|
155
|
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
156
|
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
157
|
+
|
158
|
+
The pipeline also inherits the following loading methods:
|
159
|
+
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
160
|
+
- [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
161
|
+
- [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
162
|
+
- [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
|
163
|
+
- [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
|
164
|
+
|
165
|
+
Args:
|
166
|
+
vae ([`AutoencoderKL`]):
|
167
|
+
Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
|
168
|
+
text_encoder ([`~transformers.CLIPTextModel`]):
|
169
|
+
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
170
|
+
tokenizer ([`~transformers.CLIPTokenizer`]):
|
171
|
+
A `CLIPTokenizer` to tokenize text.
|
172
|
+
unet ([`UNet2DConditionModel`]):
|
173
|
+
A `UNet2DConditionModel` to denoise the encoded image latents.
|
174
|
+
scheduler ([`SchedulerMixin`]):
|
175
|
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
176
|
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
177
|
+
safety_checker ([`StableDiffusionSafetyChecker`]):
|
178
|
+
Classification module that estimates whether generated images could be considered offensive or harmful.
|
179
|
+
Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
|
180
|
+
about a model's potential harms.
|
181
|
+
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
182
|
+
A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
|
183
|
+
"""
|
184
|
+
|
185
|
+
model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
|
186
|
+
_optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
|
187
|
+
_exclude_from_cpu_offload = ["safety_checker"]
|
188
|
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
189
|
+
|
190
|
+
def __init__(
|
191
|
+
self,
|
192
|
+
vae: AutoencoderKL,
|
193
|
+
text_encoder: CLIPTextModel,
|
194
|
+
tokenizer: CLIPTokenizer,
|
195
|
+
unet: UNet2DConditionModel,
|
196
|
+
scheduler: KarrasDiffusionSchedulers,
|
197
|
+
safety_checker: StableDiffusionSafetyChecker,
|
198
|
+
feature_extractor: CLIPImageProcessor,
|
199
|
+
image_encoder: CLIPVisionModelWithProjection = None,
|
200
|
+
requires_safety_checker: bool = True,
|
201
|
+
pag_applied_layers: Union[str, List[str]] = "mid", # ["mid"], ["down.block_1", "up.block_0.attentions_0"]
|
202
|
+
):
|
203
|
+
super().__init__()
|
204
|
+
|
205
|
+
if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
|
206
|
+
deprecation_message = (
|
207
|
+
f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
|
208
|
+
f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
|
209
|
+
"to update the config accordingly as leaving `steps_offset` might led to incorrect results"
|
210
|
+
" in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
|
211
|
+
" it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
|
212
|
+
" file"
|
213
|
+
)
|
214
|
+
deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
|
215
|
+
new_config = dict(scheduler.config)
|
216
|
+
new_config["steps_offset"] = 1
|
217
|
+
scheduler._internal_dict = FrozenDict(new_config)
|
218
|
+
|
219
|
+
if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
|
220
|
+
deprecation_message = (
|
221
|
+
f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
|
222
|
+
" `clip_sample` should be set to False in the configuration file. Please make sure to update the"
|
223
|
+
" config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
|
224
|
+
" future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
|
225
|
+
" nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
|
226
|
+
)
|
227
|
+
deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
|
228
|
+
new_config = dict(scheduler.config)
|
229
|
+
new_config["clip_sample"] = False
|
230
|
+
scheduler._internal_dict = FrozenDict(new_config)
|
231
|
+
|
232
|
+
if safety_checker is None and requires_safety_checker:
|
233
|
+
logger.warning(
|
234
|
+
f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
|
235
|
+
" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
|
236
|
+
" results in services or applications open to the public. Both the diffusers team and Hugging Face"
|
237
|
+
" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
|
238
|
+
" it only for use-cases that involve analyzing network behavior or auditing its results. For more"
|
239
|
+
" information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
|
240
|
+
)
|
241
|
+
|
242
|
+
if safety_checker is not None and feature_extractor is None:
|
243
|
+
raise ValueError(
|
244
|
+
"Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
|
245
|
+
" checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
|
246
|
+
)
|
247
|
+
|
248
|
+
is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
|
249
|
+
version.parse(unet.config._diffusers_version).base_version
|
250
|
+
) < version.parse("0.9.0.dev0")
|
251
|
+
is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
|
252
|
+
if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
|
253
|
+
deprecation_message = (
|
254
|
+
"The configuration file of the unet has set the default `sample_size` to smaller than"
|
255
|
+
" 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
|
256
|
+
" following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
|
257
|
+
" CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
|
258
|
+
" \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
|
259
|
+
" configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
|
260
|
+
" in the config might lead to incorrect results in future versions. If you have downloaded this"
|
261
|
+
" checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
|
262
|
+
" the `unet/config.json` file"
|
263
|
+
)
|
264
|
+
deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
|
265
|
+
new_config = dict(unet.config)
|
266
|
+
new_config["sample_size"] = 64
|
267
|
+
unet._internal_dict = FrozenDict(new_config)
|
268
|
+
|
269
|
+
self.register_modules(
|
270
|
+
vae=vae,
|
271
|
+
text_encoder=text_encoder,
|
272
|
+
tokenizer=tokenizer,
|
273
|
+
unet=unet,
|
274
|
+
scheduler=scheduler,
|
275
|
+
safety_checker=safety_checker,
|
276
|
+
feature_extractor=feature_extractor,
|
277
|
+
image_encoder=image_encoder,
|
278
|
+
)
|
279
|
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
280
|
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
281
|
+
self.register_to_config(requires_safety_checker=requires_safety_checker)
|
282
|
+
|
283
|
+
self.set_pag_applied_layers(pag_applied_layers)
|
284
|
+
|
285
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt
|
286
|
+
def encode_prompt(
|
287
|
+
self,
|
288
|
+
prompt,
|
289
|
+
device,
|
290
|
+
num_images_per_prompt,
|
291
|
+
do_classifier_free_guidance,
|
292
|
+
negative_prompt=None,
|
293
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
294
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
295
|
+
lora_scale: Optional[float] = None,
|
296
|
+
clip_skip: Optional[int] = None,
|
297
|
+
):
|
298
|
+
r"""
|
299
|
+
Encodes the prompt into text encoder hidden states.
|
300
|
+
|
301
|
+
Args:
|
302
|
+
prompt (`str` or `List[str]`, *optional*):
|
303
|
+
prompt to be encoded
|
304
|
+
device: (`torch.device`):
|
305
|
+
torch device
|
306
|
+
num_images_per_prompt (`int`):
|
307
|
+
number of images that should be generated per prompt
|
308
|
+
do_classifier_free_guidance (`bool`):
|
309
|
+
whether to use classifier free guidance or not
|
310
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
311
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
312
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
313
|
+
less than `1`).
|
314
|
+
prompt_embeds (`torch.Tensor`, *optional*):
|
315
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
316
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
317
|
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
318
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
319
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
320
|
+
argument.
|
321
|
+
lora_scale (`float`, *optional*):
|
322
|
+
A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
323
|
+
clip_skip (`int`, *optional*):
|
324
|
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
325
|
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
326
|
+
"""
|
327
|
+
# set lora scale so that monkey patched LoRA
|
328
|
+
# function of text encoder can correctly access it
|
329
|
+
if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
|
330
|
+
self._lora_scale = lora_scale
|
331
|
+
|
332
|
+
# dynamically adjust the LoRA scale
|
333
|
+
if not USE_PEFT_BACKEND:
|
334
|
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
335
|
+
else:
|
336
|
+
scale_lora_layers(self.text_encoder, lora_scale)
|
337
|
+
|
338
|
+
if prompt is not None and isinstance(prompt, str):
|
339
|
+
batch_size = 1
|
340
|
+
elif prompt is not None and isinstance(prompt, list):
|
341
|
+
batch_size = len(prompt)
|
342
|
+
else:
|
343
|
+
batch_size = prompt_embeds.shape[0]
|
344
|
+
|
345
|
+
if prompt_embeds is None:
|
346
|
+
# textual inversion: process multi-vector tokens if necessary
|
347
|
+
if isinstance(self, TextualInversionLoaderMixin):
|
348
|
+
prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
|
349
|
+
|
350
|
+
text_inputs = self.tokenizer(
|
351
|
+
prompt,
|
352
|
+
padding="max_length",
|
353
|
+
max_length=self.tokenizer.model_max_length,
|
354
|
+
truncation=True,
|
355
|
+
return_tensors="pt",
|
356
|
+
)
|
357
|
+
text_input_ids = text_inputs.input_ids
|
358
|
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
359
|
+
|
360
|
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
361
|
+
text_input_ids, untruncated_ids
|
362
|
+
):
|
363
|
+
removed_text = self.tokenizer.batch_decode(
|
364
|
+
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
|
365
|
+
)
|
366
|
+
logger.warning(
|
367
|
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
368
|
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
369
|
+
)
|
370
|
+
|
371
|
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
372
|
+
attention_mask = text_inputs.attention_mask.to(device)
|
373
|
+
else:
|
374
|
+
attention_mask = None
|
375
|
+
|
376
|
+
if clip_skip is None:
|
377
|
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
|
378
|
+
prompt_embeds = prompt_embeds[0]
|
379
|
+
else:
|
380
|
+
prompt_embeds = self.text_encoder(
|
381
|
+
text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
|
382
|
+
)
|
383
|
+
# Access the `hidden_states` first, that contains a tuple of
|
384
|
+
# all the hidden states from the encoder layers. Then index into
|
385
|
+
# the tuple to access the hidden states from the desired layer.
|
386
|
+
prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
|
387
|
+
# We also need to apply the final LayerNorm here to not mess with the
|
388
|
+
# representations. The `last_hidden_states` that we typically use for
|
389
|
+
# obtaining the final prompt representations passes through the LayerNorm
|
390
|
+
# layer.
|
391
|
+
prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
|
392
|
+
|
393
|
+
if self.text_encoder is not None:
|
394
|
+
prompt_embeds_dtype = self.text_encoder.dtype
|
395
|
+
elif self.unet is not None:
|
396
|
+
prompt_embeds_dtype = self.unet.dtype
|
397
|
+
else:
|
398
|
+
prompt_embeds_dtype = prompt_embeds.dtype
|
399
|
+
|
400
|
+
prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
401
|
+
|
402
|
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
403
|
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
404
|
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
405
|
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
406
|
+
|
407
|
+
# get unconditional embeddings for classifier free guidance
|
408
|
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
409
|
+
uncond_tokens: List[str]
|
410
|
+
if negative_prompt is None:
|
411
|
+
uncond_tokens = [""] * batch_size
|
412
|
+
elif prompt is not None and type(prompt) is not type(negative_prompt):
|
413
|
+
raise TypeError(
|
414
|
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
415
|
+
f" {type(prompt)}."
|
416
|
+
)
|
417
|
+
elif isinstance(negative_prompt, str):
|
418
|
+
uncond_tokens = [negative_prompt]
|
419
|
+
elif batch_size != len(negative_prompt):
|
420
|
+
raise ValueError(
|
421
|
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
422
|
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
423
|
+
" the batch size of `prompt`."
|
424
|
+
)
|
425
|
+
else:
|
426
|
+
uncond_tokens = negative_prompt
|
427
|
+
|
428
|
+
# textual inversion: process multi-vector tokens if necessary
|
429
|
+
if isinstance(self, TextualInversionLoaderMixin):
|
430
|
+
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
|
431
|
+
|
432
|
+
max_length = prompt_embeds.shape[1]
|
433
|
+
uncond_input = self.tokenizer(
|
434
|
+
uncond_tokens,
|
435
|
+
padding="max_length",
|
436
|
+
max_length=max_length,
|
437
|
+
truncation=True,
|
438
|
+
return_tensors="pt",
|
439
|
+
)
|
440
|
+
|
441
|
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
442
|
+
attention_mask = uncond_input.attention_mask.to(device)
|
443
|
+
else:
|
444
|
+
attention_mask = None
|
445
|
+
|
446
|
+
negative_prompt_embeds = self.text_encoder(
|
447
|
+
uncond_input.input_ids.to(device),
|
448
|
+
attention_mask=attention_mask,
|
449
|
+
)
|
450
|
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
451
|
+
|
452
|
+
if do_classifier_free_guidance:
|
453
|
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
454
|
+
seq_len = negative_prompt_embeds.shape[1]
|
455
|
+
|
456
|
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
457
|
+
|
458
|
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
459
|
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
460
|
+
|
461
|
+
if self.text_encoder is not None:
|
462
|
+
if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
|
463
|
+
# Retrieve the original scale by scaling back the LoRA layers
|
464
|
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
465
|
+
|
466
|
+
return prompt_embeds, negative_prompt_embeds
|
467
|
+
|
468
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
|
469
|
+
def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
|
470
|
+
dtype = next(self.image_encoder.parameters()).dtype
|
471
|
+
|
472
|
+
if not isinstance(image, torch.Tensor):
|
473
|
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
474
|
+
|
475
|
+
image = image.to(device=device, dtype=dtype)
|
476
|
+
if output_hidden_states:
|
477
|
+
image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
|
478
|
+
image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
|
479
|
+
uncond_image_enc_hidden_states = self.image_encoder(
|
480
|
+
torch.zeros_like(image), output_hidden_states=True
|
481
|
+
).hidden_states[-2]
|
482
|
+
uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
|
483
|
+
num_images_per_prompt, dim=0
|
484
|
+
)
|
485
|
+
return image_enc_hidden_states, uncond_image_enc_hidden_states
|
486
|
+
else:
|
487
|
+
image_embeds = self.image_encoder(image).image_embeds
|
488
|
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
489
|
+
uncond_image_embeds = torch.zeros_like(image_embeds)
|
490
|
+
|
491
|
+
return image_embeds, uncond_image_embeds
|
492
|
+
|
493
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
|
494
|
+
def prepare_ip_adapter_image_embeds(
|
495
|
+
self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
|
496
|
+
):
|
497
|
+
image_embeds = []
|
498
|
+
if do_classifier_free_guidance:
|
499
|
+
negative_image_embeds = []
|
500
|
+
if ip_adapter_image_embeds is None:
|
501
|
+
if not isinstance(ip_adapter_image, list):
|
502
|
+
ip_adapter_image = [ip_adapter_image]
|
503
|
+
|
504
|
+
if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
|
505
|
+
raise ValueError(
|
506
|
+
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."
|
507
|
+
)
|
508
|
+
|
509
|
+
for single_ip_adapter_image, image_proj_layer in zip(
|
510
|
+
ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
|
511
|
+
):
|
512
|
+
output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
|
513
|
+
single_image_embeds, single_negative_image_embeds = self.encode_image(
|
514
|
+
single_ip_adapter_image, device, 1, output_hidden_state
|
515
|
+
)
|
516
|
+
|
517
|
+
image_embeds.append(single_image_embeds[None, :])
|
518
|
+
if do_classifier_free_guidance:
|
519
|
+
negative_image_embeds.append(single_negative_image_embeds[None, :])
|
520
|
+
else:
|
521
|
+
for single_image_embeds in ip_adapter_image_embeds:
|
522
|
+
if do_classifier_free_guidance:
|
523
|
+
single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
|
524
|
+
negative_image_embeds.append(single_negative_image_embeds)
|
525
|
+
image_embeds.append(single_image_embeds)
|
526
|
+
|
527
|
+
ip_adapter_image_embeds = []
|
528
|
+
for i, single_image_embeds in enumerate(image_embeds):
|
529
|
+
single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
|
530
|
+
if do_classifier_free_guidance:
|
531
|
+
single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
|
532
|
+
single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
|
533
|
+
|
534
|
+
single_image_embeds = single_image_embeds.to(device=device)
|
535
|
+
ip_adapter_image_embeds.append(single_image_embeds)
|
536
|
+
|
537
|
+
return ip_adapter_image_embeds
|
538
|
+
|
539
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
|
540
|
+
def run_safety_checker(self, image, device, dtype):
|
541
|
+
if self.safety_checker is None:
|
542
|
+
has_nsfw_concept = None
|
543
|
+
else:
|
544
|
+
if torch.is_tensor(image):
|
545
|
+
feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
|
546
|
+
else:
|
547
|
+
feature_extractor_input = self.image_processor.numpy_to_pil(image)
|
548
|
+
safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
|
549
|
+
image, has_nsfw_concept = self.safety_checker(
|
550
|
+
images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
|
551
|
+
)
|
552
|
+
return image, has_nsfw_concept
|
553
|
+
|
554
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
555
|
+
def prepare_extra_step_kwargs(self, generator, eta):
|
556
|
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
557
|
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
558
|
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
559
|
+
# and should be between [0, 1]
|
560
|
+
|
561
|
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
562
|
+
extra_step_kwargs = {}
|
563
|
+
if accepts_eta:
|
564
|
+
extra_step_kwargs["eta"] = eta
|
565
|
+
|
566
|
+
# check if the scheduler accepts generator
|
567
|
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
568
|
+
if accepts_generator:
|
569
|
+
extra_step_kwargs["generator"] = generator
|
570
|
+
return extra_step_kwargs
|
571
|
+
|
572
|
+
def check_inputs(
|
573
|
+
self,
|
574
|
+
prompt,
|
575
|
+
strength,
|
576
|
+
negative_prompt=None,
|
577
|
+
prompt_embeds=None,
|
578
|
+
negative_prompt_embeds=None,
|
579
|
+
ip_adapter_image=None,
|
580
|
+
ip_adapter_image_embeds=None,
|
581
|
+
callback_on_step_end_tensor_inputs=None,
|
582
|
+
):
|
583
|
+
if strength < 0 or strength > 1:
|
584
|
+
raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
|
585
|
+
|
586
|
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
587
|
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
588
|
+
):
|
589
|
+
raise ValueError(
|
590
|
+
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]}"
|
591
|
+
)
|
592
|
+
if prompt is not None and prompt_embeds is not None:
|
593
|
+
raise ValueError(
|
594
|
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
595
|
+
" only forward one of the two."
|
596
|
+
)
|
597
|
+
elif prompt is None and prompt_embeds is None:
|
598
|
+
raise ValueError(
|
599
|
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
600
|
+
)
|
601
|
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
602
|
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
603
|
+
|
604
|
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
605
|
+
raise ValueError(
|
606
|
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
607
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
608
|
+
)
|
609
|
+
|
610
|
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
611
|
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
612
|
+
raise ValueError(
|
613
|
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
614
|
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
615
|
+
f" {negative_prompt_embeds.shape}."
|
616
|
+
)
|
617
|
+
|
618
|
+
if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
|
619
|
+
raise ValueError(
|
620
|
+
"Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
|
621
|
+
)
|
622
|
+
|
623
|
+
if ip_adapter_image_embeds is not None:
|
624
|
+
if not isinstance(ip_adapter_image_embeds, list):
|
625
|
+
raise ValueError(
|
626
|
+
f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
|
627
|
+
)
|
628
|
+
elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
|
629
|
+
raise ValueError(
|
630
|
+
f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
|
631
|
+
)
|
632
|
+
|
633
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps
|
634
|
+
def get_timesteps(self, num_inference_steps, strength, device):
|
635
|
+
# get the original timestep using init_timestep
|
636
|
+
init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
|
637
|
+
|
638
|
+
t_start = max(num_inference_steps - init_timestep, 0)
|
639
|
+
timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
|
640
|
+
if hasattr(self.scheduler, "set_begin_index"):
|
641
|
+
self.scheduler.set_begin_index(t_start * self.scheduler.order)
|
642
|
+
|
643
|
+
return timesteps, num_inference_steps - t_start
|
644
|
+
|
645
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.prepare_latents
|
646
|
+
def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
|
647
|
+
if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
|
648
|
+
raise ValueError(
|
649
|
+
f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
|
650
|
+
)
|
651
|
+
|
652
|
+
image = image.to(device=device, dtype=dtype)
|
653
|
+
|
654
|
+
batch_size = batch_size * num_images_per_prompt
|
655
|
+
|
656
|
+
if image.shape[1] == 4:
|
657
|
+
init_latents = image
|
658
|
+
|
659
|
+
else:
|
660
|
+
if isinstance(generator, list) and len(generator) != batch_size:
|
661
|
+
raise ValueError(
|
662
|
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
663
|
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
664
|
+
)
|
665
|
+
|
666
|
+
elif isinstance(generator, list):
|
667
|
+
if image.shape[0] < batch_size and batch_size % image.shape[0] == 0:
|
668
|
+
image = torch.cat([image] * (batch_size // image.shape[0]), dim=0)
|
669
|
+
elif image.shape[0] < batch_size and batch_size % image.shape[0] != 0:
|
670
|
+
raise ValueError(
|
671
|
+
f"Cannot duplicate `image` of batch size {image.shape[0]} to effective batch_size {batch_size} "
|
672
|
+
)
|
673
|
+
|
674
|
+
init_latents = [
|
675
|
+
retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
|
676
|
+
for i in range(batch_size)
|
677
|
+
]
|
678
|
+
init_latents = torch.cat(init_latents, dim=0)
|
679
|
+
else:
|
680
|
+
init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
|
681
|
+
|
682
|
+
init_latents = self.vae.config.scaling_factor * init_latents
|
683
|
+
|
684
|
+
if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
|
685
|
+
# expand init_latents for batch_size
|
686
|
+
deprecation_message = (
|
687
|
+
f"You have passed {batch_size} text prompts (`prompt`), but only {init_latents.shape[0]} initial"
|
688
|
+
" images (`image`). Initial images are now duplicating to match the number of text prompts. Note"
|
689
|
+
" that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update"
|
690
|
+
" your script to pass as many initial images as text prompts to suppress this warning."
|
691
|
+
)
|
692
|
+
deprecate("len(prompt) != len(image)", "1.0.0", deprecation_message, standard_warn=False)
|
693
|
+
additional_image_per_prompt = batch_size // init_latents.shape[0]
|
694
|
+
init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
|
695
|
+
elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
|
696
|
+
raise ValueError(
|
697
|
+
f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
|
698
|
+
)
|
699
|
+
else:
|
700
|
+
init_latents = torch.cat([init_latents], dim=0)
|
701
|
+
|
702
|
+
shape = init_latents.shape
|
703
|
+
noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
704
|
+
|
705
|
+
# get latents
|
706
|
+
init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
|
707
|
+
latents = init_latents
|
708
|
+
|
709
|
+
return latents
|
710
|
+
|
711
|
+
# Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
|
712
|
+
def get_guidance_scale_embedding(
|
713
|
+
self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
|
714
|
+
) -> torch.Tensor:
|
715
|
+
"""
|
716
|
+
See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
|
717
|
+
|
718
|
+
Args:
|
719
|
+
w (`torch.Tensor`):
|
720
|
+
Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
|
721
|
+
embedding_dim (`int`, *optional*, defaults to 512):
|
722
|
+
Dimension of the embeddings to generate.
|
723
|
+
dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
|
724
|
+
Data type of the generated embeddings.
|
725
|
+
|
726
|
+
Returns:
|
727
|
+
`torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
|
728
|
+
"""
|
729
|
+
assert len(w.shape) == 1
|
730
|
+
w = w * 1000.0
|
731
|
+
|
732
|
+
half_dim = embedding_dim // 2
|
733
|
+
emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
|
734
|
+
emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
|
735
|
+
emb = w.to(dtype)[:, None] * emb[None, :]
|
736
|
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
737
|
+
if embedding_dim % 2 == 1: # zero pad
|
738
|
+
emb = torch.nn.functional.pad(emb, (0, 1))
|
739
|
+
assert emb.shape == (w.shape[0], embedding_dim)
|
740
|
+
return emb
|
741
|
+
|
742
|
+
@property
|
743
|
+
def guidance_scale(self):
|
744
|
+
return self._guidance_scale
|
745
|
+
|
746
|
+
@property
|
747
|
+
def clip_skip(self):
|
748
|
+
return self._clip_skip
|
749
|
+
|
750
|
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
751
|
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
752
|
+
# corresponds to doing no classifier free guidance.
|
753
|
+
@property
|
754
|
+
def do_classifier_free_guidance(self):
|
755
|
+
return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
|
756
|
+
|
757
|
+
@property
|
758
|
+
def cross_attention_kwargs(self):
|
759
|
+
return self._cross_attention_kwargs
|
760
|
+
|
761
|
+
@property
|
762
|
+
def num_timesteps(self):
|
763
|
+
return self._num_timesteps
|
764
|
+
|
765
|
+
@property
|
766
|
+
def interrupt(self):
|
767
|
+
return self._interrupt
|
768
|
+
|
769
|
+
@torch.no_grad()
|
770
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
771
|
+
def __call__(
|
772
|
+
self,
|
773
|
+
prompt: Union[str, List[str]] = None,
|
774
|
+
image: PipelineImageInput = None,
|
775
|
+
strength: float = 0.8,
|
776
|
+
num_inference_steps: Optional[int] = 50,
|
777
|
+
timesteps: List[int] = None,
|
778
|
+
sigmas: List[float] = None,
|
779
|
+
guidance_scale: Optional[float] = 7.5,
|
780
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
781
|
+
num_images_per_prompt: Optional[int] = 1,
|
782
|
+
eta: Optional[float] = 0.0,
|
783
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
784
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
785
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
786
|
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
787
|
+
ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
|
788
|
+
output_type: Optional[str] = "pil",
|
789
|
+
return_dict: bool = True,
|
790
|
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
791
|
+
clip_skip: int = None,
|
792
|
+
callback_on_step_end: Optional[
|
793
|
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
794
|
+
] = None,
|
795
|
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
796
|
+
pag_scale: float = 3.0,
|
797
|
+
pag_adaptive_scale: float = 0.0,
|
798
|
+
):
|
799
|
+
r"""
|
800
|
+
The call function to the pipeline for generation.
|
801
|
+
|
802
|
+
Args:
|
803
|
+
prompt (`str` or `List[str]`, *optional*):
|
804
|
+
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
805
|
+
image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
|
806
|
+
`Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
|
807
|
+
numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
|
808
|
+
or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
|
809
|
+
list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
|
810
|
+
latents as `image`, but if passing latents directly it is not encoded again.
|
811
|
+
strength (`float`, *optional*, defaults to 0.8):
|
812
|
+
Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
|
813
|
+
starting point and more noise is added the higher the `strength`. The number of denoising steps depends
|
814
|
+
on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
|
815
|
+
process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
|
816
|
+
essentially ignores `image`.
|
817
|
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
818
|
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
819
|
+
expense of slower inference. This parameter is modulated by `strength`.
|
820
|
+
timesteps (`List[int]`, *optional*):
|
821
|
+
Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
|
822
|
+
in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
|
823
|
+
passed will be used. Must be in descending order.
|
824
|
+
sigmas (`List[float]`, *optional*):
|
825
|
+
Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
|
826
|
+
their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
|
827
|
+
will be used.
|
828
|
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
829
|
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
830
|
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
831
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
832
|
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
833
|
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
834
|
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
835
|
+
The number of images to generate per prompt.
|
836
|
+
eta (`float`, *optional*, defaults to 0.0):
|
837
|
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
838
|
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
839
|
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
840
|
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
841
|
+
generation deterministic.
|
842
|
+
prompt_embeds (`torch.Tensor`, *optional*):
|
843
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
844
|
+
provided, text embeddings are generated from the `prompt` input argument.
|
845
|
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
846
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
847
|
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
848
|
+
ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
|
849
|
+
ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
|
850
|
+
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
|
851
|
+
IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
|
852
|
+
contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
|
853
|
+
provided, embeddings are computed from the `ip_adapter_image` input argument.
|
854
|
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
855
|
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
856
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
857
|
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
858
|
+
plain tuple.
|
859
|
+
cross_attention_kwargs (`dict`, *optional*):
|
860
|
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
861
|
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
862
|
+
clip_skip (`int`, *optional*):
|
863
|
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
864
|
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
865
|
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
866
|
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
867
|
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
868
|
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
869
|
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
870
|
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
871
|
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
872
|
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
873
|
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
874
|
+
pag_scale (`float`, *optional*, defaults to 3.0):
|
875
|
+
The scale factor for the perturbed attention guidance. If it is set to 0.0, the perturbed attention
|
876
|
+
guidance will not be used.
|
877
|
+
pag_adaptive_scale (`float`, *optional*, defaults to 0.0):
|
878
|
+
The adaptive scale factor for the perturbed attention guidance. If it is set to 0.0, `pag_scale` is
|
879
|
+
used.
|
880
|
+
|
881
|
+
Examples:
|
882
|
+
|
883
|
+
Returns:
|
884
|
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
885
|
+
If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
|
886
|
+
otherwise a `tuple` is returned where the first element is a list with the generated images and the
|
887
|
+
second element is a list of `bool`s indicating whether the corresponding generated image contains
|
888
|
+
"not-safe-for-work" (nsfw) content.
|
889
|
+
"""
|
890
|
+
|
891
|
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
892
|
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
893
|
+
|
894
|
+
# 1. Check inputs. Raise error if not correct
|
895
|
+
self.check_inputs(
|
896
|
+
prompt,
|
897
|
+
strength,
|
898
|
+
negative_prompt,
|
899
|
+
prompt_embeds,
|
900
|
+
negative_prompt_embeds,
|
901
|
+
ip_adapter_image,
|
902
|
+
ip_adapter_image_embeds,
|
903
|
+
callback_on_step_end_tensor_inputs,
|
904
|
+
)
|
905
|
+
|
906
|
+
self._guidance_scale = guidance_scale
|
907
|
+
self._clip_skip = clip_skip
|
908
|
+
self._cross_attention_kwargs = cross_attention_kwargs
|
909
|
+
self._interrupt = False
|
910
|
+
|
911
|
+
self._pag_scale = pag_scale
|
912
|
+
self._pag_adaptive_scale = pag_adaptive_scale
|
913
|
+
|
914
|
+
# 2. Define call parameters
|
915
|
+
if prompt is not None and isinstance(prompt, str):
|
916
|
+
batch_size = 1
|
917
|
+
elif prompt is not None and isinstance(prompt, list):
|
918
|
+
batch_size = len(prompt)
|
919
|
+
else:
|
920
|
+
batch_size = prompt_embeds.shape[0]
|
921
|
+
|
922
|
+
device = self._execution_device
|
923
|
+
|
924
|
+
# 3. Encode input prompt
|
925
|
+
text_encoder_lora_scale = (
|
926
|
+
self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
|
927
|
+
)
|
928
|
+
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
929
|
+
prompt,
|
930
|
+
device,
|
931
|
+
num_images_per_prompt,
|
932
|
+
self.do_classifier_free_guidance,
|
933
|
+
negative_prompt,
|
934
|
+
prompt_embeds=prompt_embeds,
|
935
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
936
|
+
lora_scale=text_encoder_lora_scale,
|
937
|
+
clip_skip=self.clip_skip,
|
938
|
+
)
|
939
|
+
# For classifier free guidance, we need to do two forward passes.
|
940
|
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
941
|
+
# to avoid doing two forward passes
|
942
|
+
if self.do_perturbed_attention_guidance:
|
943
|
+
prompt_embeds = self._prepare_perturbed_attention_guidance(
|
944
|
+
prompt_embeds, negative_prompt_embeds, self.do_classifier_free_guidance
|
945
|
+
)
|
946
|
+
elif self.do_classifier_free_guidance:
|
947
|
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
948
|
+
|
949
|
+
if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
|
950
|
+
ip_adapter_image_embeds = self.prepare_ip_adapter_image_embeds(
|
951
|
+
ip_adapter_image,
|
952
|
+
ip_adapter_image_embeds,
|
953
|
+
device,
|
954
|
+
batch_size * num_images_per_prompt,
|
955
|
+
self.do_classifier_free_guidance,
|
956
|
+
)
|
957
|
+
|
958
|
+
for i, image_embeds in enumerate(ip_adapter_image_embeds):
|
959
|
+
negative_image_embeds = None
|
960
|
+
if self.do_classifier_free_guidance:
|
961
|
+
negative_image_embeds, image_embeds = image_embeds.chunk(2)
|
962
|
+
if self.do_perturbed_attention_guidance:
|
963
|
+
image_embeds = self._prepare_perturbed_attention_guidance(
|
964
|
+
image_embeds, negative_image_embeds, self.do_classifier_free_guidance
|
965
|
+
)
|
966
|
+
|
967
|
+
elif self.do_classifier_free_guidance:
|
968
|
+
image_embeds = torch.cat([negative_image_embeds, image_embeds], dim=0)
|
969
|
+
image_embeds = image_embeds.to(device)
|
970
|
+
ip_adapter_image_embeds[i] = image_embeds
|
971
|
+
|
972
|
+
# 4. Preprocess image
|
973
|
+
image = self.image_processor.preprocess(image)
|
974
|
+
|
975
|
+
# 5. set timesteps
|
976
|
+
timesteps, num_inference_steps = retrieve_timesteps(
|
977
|
+
self.scheduler, num_inference_steps, device, timesteps, sigmas
|
978
|
+
)
|
979
|
+
timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
|
980
|
+
latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
|
981
|
+
|
982
|
+
# 6. Prepare latent variables
|
983
|
+
latents = self.prepare_latents(
|
984
|
+
image,
|
985
|
+
latent_timestep,
|
986
|
+
batch_size,
|
987
|
+
num_images_per_prompt,
|
988
|
+
prompt_embeds.dtype,
|
989
|
+
device,
|
990
|
+
generator,
|
991
|
+
)
|
992
|
+
|
993
|
+
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
994
|
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
995
|
+
|
996
|
+
# 7.1 Add image embeds for IP-Adapter
|
997
|
+
added_cond_kwargs = (
|
998
|
+
{"image_embeds": image_embeds}
|
999
|
+
if ip_adapter_image is not None or ip_adapter_image_embeds is not None
|
1000
|
+
else None
|
1001
|
+
)
|
1002
|
+
|
1003
|
+
# 7.2 Optionally get Guidance Scale Embedding
|
1004
|
+
timestep_cond = None
|
1005
|
+
if self.unet.config.time_cond_proj_dim is not None:
|
1006
|
+
guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
|
1007
|
+
timestep_cond = self.get_guidance_scale_embedding(
|
1008
|
+
guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
|
1009
|
+
).to(device=device, dtype=latents.dtype)
|
1010
|
+
|
1011
|
+
# 8. Denoising loop
|
1012
|
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
1013
|
+
if self.do_perturbed_attention_guidance:
|
1014
|
+
original_attn_proc = self.unet.attn_processors
|
1015
|
+
self._set_pag_attn_processor(
|
1016
|
+
pag_applied_layers=self.pag_applied_layers,
|
1017
|
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
1018
|
+
)
|
1019
|
+
self._num_timesteps = len(timesteps)
|
1020
|
+
|
1021
|
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
1022
|
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
1023
|
+
for i, t in enumerate(timesteps):
|
1024
|
+
if self.interrupt:
|
1025
|
+
continue
|
1026
|
+
|
1027
|
+
# expand the latents if we are doing classifier free guidance
|
1028
|
+
latent_model_input = torch.cat([latents] * (prompt_embeds.shape[0] // latents.shape[0]))
|
1029
|
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
1030
|
+
|
1031
|
+
# predict the noise residual
|
1032
|
+
if ip_adapter_image_embeds is not None:
|
1033
|
+
added_cond_kwargs["image_embeds"] = ip_adapter_image_embeds
|
1034
|
+
noise_pred = self.unet(
|
1035
|
+
latent_model_input,
|
1036
|
+
t,
|
1037
|
+
encoder_hidden_states=prompt_embeds,
|
1038
|
+
timestep_cond=timestep_cond,
|
1039
|
+
cross_attention_kwargs=self.cross_attention_kwargs,
|
1040
|
+
added_cond_kwargs=added_cond_kwargs,
|
1041
|
+
return_dict=False,
|
1042
|
+
)[0]
|
1043
|
+
|
1044
|
+
# perform guidance
|
1045
|
+
if self.do_perturbed_attention_guidance:
|
1046
|
+
noise_pred = self._apply_perturbed_attention_guidance(
|
1047
|
+
noise_pred, self.do_classifier_free_guidance, self.guidance_scale, t
|
1048
|
+
)
|
1049
|
+
elif self.do_classifier_free_guidance:
|
1050
|
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
1051
|
+
noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
|
1052
|
+
|
1053
|
+
# compute the previous noisy sample x_t -> x_t-1
|
1054
|
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
1055
|
+
|
1056
|
+
if callback_on_step_end is not None:
|
1057
|
+
callback_kwargs = {}
|
1058
|
+
for k in callback_on_step_end_tensor_inputs:
|
1059
|
+
callback_kwargs[k] = locals()[k]
|
1060
|
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
1061
|
+
|
1062
|
+
latents = callback_outputs.pop("latents", latents)
|
1063
|
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
1064
|
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
1065
|
+
|
1066
|
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
1067
|
+
progress_bar.update()
|
1068
|
+
|
1069
|
+
if not output_type == "latent":
|
1070
|
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
|
1071
|
+
0
|
1072
|
+
]
|
1073
|
+
image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
|
1074
|
+
else:
|
1075
|
+
image = latents
|
1076
|
+
has_nsfw_concept = None
|
1077
|
+
|
1078
|
+
if has_nsfw_concept is None:
|
1079
|
+
do_denormalize = [True] * image.shape[0]
|
1080
|
+
else:
|
1081
|
+
do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
|
1082
|
+
|
1083
|
+
image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
|
1084
|
+
|
1085
|
+
# Offload all models
|
1086
|
+
self.maybe_free_model_hooks()
|
1087
|
+
|
1088
|
+
if self.do_perturbed_attention_guidance:
|
1089
|
+
self.unet.set_attn_processor(original_attn_proc)
|
1090
|
+
|
1091
|
+
if not return_dict:
|
1092
|
+
return (image, has_nsfw_concept)
|
1093
|
+
|
1094
|
+
return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
|