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,1140 @@
|
|
1
|
+
# Copyright 2024 Stability AI, The HuggingFace Team and The InstantX 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 torch
|
19
|
+
from transformers import (
|
20
|
+
BaseImageProcessor,
|
21
|
+
CLIPTextModelWithProjection,
|
22
|
+
CLIPTokenizer,
|
23
|
+
PreTrainedModel,
|
24
|
+
T5EncoderModel,
|
25
|
+
T5TokenizerFast,
|
26
|
+
)
|
27
|
+
|
28
|
+
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
29
|
+
from ...loaders import FromSingleFileMixin, SD3IPAdapterMixin, SD3LoraLoaderMixin
|
30
|
+
from ...models.autoencoders import AutoencoderKL
|
31
|
+
from ...models.transformers import SD3Transformer2DModel
|
32
|
+
from ...schedulers import FlowMatchEulerDiscreteScheduler
|
33
|
+
from ...utils import (
|
34
|
+
USE_PEFT_BACKEND,
|
35
|
+
is_torch_xla_available,
|
36
|
+
logging,
|
37
|
+
replace_example_docstring,
|
38
|
+
scale_lora_layers,
|
39
|
+
unscale_lora_layers,
|
40
|
+
)
|
41
|
+
from ...utils.torch_utils import randn_tensor
|
42
|
+
from ..pipeline_utils import DiffusionPipeline
|
43
|
+
from .pipeline_output import StableDiffusion3PipelineOutput
|
44
|
+
|
45
|
+
|
46
|
+
if is_torch_xla_available():
|
47
|
+
import torch_xla.core.xla_model as xm
|
48
|
+
|
49
|
+
XLA_AVAILABLE = True
|
50
|
+
else:
|
51
|
+
XLA_AVAILABLE = False
|
52
|
+
|
53
|
+
|
54
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
55
|
+
|
56
|
+
EXAMPLE_DOC_STRING = """
|
57
|
+
Examples:
|
58
|
+
```py
|
59
|
+
>>> import torch
|
60
|
+
>>> from diffusers import StableDiffusion3Pipeline
|
61
|
+
|
62
|
+
>>> pipe = StableDiffusion3Pipeline.from_pretrained(
|
63
|
+
... "stabilityai/stable-diffusion-3-medium-diffusers", torch_dtype=torch.float16
|
64
|
+
... )
|
65
|
+
>>> pipe.to("cuda")
|
66
|
+
>>> prompt = "A cat holding a sign that says hello world"
|
67
|
+
>>> image = pipe(prompt).images[0]
|
68
|
+
>>> image.save("sd3.png")
|
69
|
+
```
|
70
|
+
"""
|
71
|
+
|
72
|
+
|
73
|
+
# Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
|
74
|
+
def calculate_shift(
|
75
|
+
image_seq_len,
|
76
|
+
base_seq_len: int = 256,
|
77
|
+
max_seq_len: int = 4096,
|
78
|
+
base_shift: float = 0.5,
|
79
|
+
max_shift: float = 1.16,
|
80
|
+
):
|
81
|
+
m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
|
82
|
+
b = base_shift - m * base_seq_len
|
83
|
+
mu = image_seq_len * m + b
|
84
|
+
return mu
|
85
|
+
|
86
|
+
|
87
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
88
|
+
def retrieve_timesteps(
|
89
|
+
scheduler,
|
90
|
+
num_inference_steps: Optional[int] = None,
|
91
|
+
device: Optional[Union[str, torch.device]] = None,
|
92
|
+
timesteps: Optional[List[int]] = None,
|
93
|
+
sigmas: Optional[List[float]] = None,
|
94
|
+
**kwargs,
|
95
|
+
):
|
96
|
+
r"""
|
97
|
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
98
|
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
99
|
+
|
100
|
+
Args:
|
101
|
+
scheduler (`SchedulerMixin`):
|
102
|
+
The scheduler to get timesteps from.
|
103
|
+
num_inference_steps (`int`):
|
104
|
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
105
|
+
must be `None`.
|
106
|
+
device (`str` or `torch.device`, *optional*):
|
107
|
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
108
|
+
timesteps (`List[int]`, *optional*):
|
109
|
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
110
|
+
`num_inference_steps` and `sigmas` must be `None`.
|
111
|
+
sigmas (`List[float]`, *optional*):
|
112
|
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
113
|
+
`num_inference_steps` and `timesteps` must be `None`.
|
114
|
+
|
115
|
+
Returns:
|
116
|
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
117
|
+
second element is the number of inference steps.
|
118
|
+
"""
|
119
|
+
if timesteps is not None and sigmas is not None:
|
120
|
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
121
|
+
if timesteps is not None:
|
122
|
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
123
|
+
if not accepts_timesteps:
|
124
|
+
raise ValueError(
|
125
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
126
|
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
127
|
+
)
|
128
|
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
129
|
+
timesteps = scheduler.timesteps
|
130
|
+
num_inference_steps = len(timesteps)
|
131
|
+
elif sigmas is not None:
|
132
|
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
133
|
+
if not accept_sigmas:
|
134
|
+
raise ValueError(
|
135
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
136
|
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
137
|
+
)
|
138
|
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
139
|
+
timesteps = scheduler.timesteps
|
140
|
+
num_inference_steps = len(timesteps)
|
141
|
+
else:
|
142
|
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
143
|
+
timesteps = scheduler.timesteps
|
144
|
+
return timesteps, num_inference_steps
|
145
|
+
|
146
|
+
|
147
|
+
class StableDiffusion3Pipeline(DiffusionPipeline, SD3LoraLoaderMixin, FromSingleFileMixin, SD3IPAdapterMixin):
|
148
|
+
r"""
|
149
|
+
Args:
|
150
|
+
transformer ([`SD3Transformer2DModel`]):
|
151
|
+
Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
|
152
|
+
scheduler ([`FlowMatchEulerDiscreteScheduler`]):
|
153
|
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
154
|
+
vae ([`AutoencoderKL`]):
|
155
|
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
156
|
+
text_encoder ([`CLIPTextModelWithProjection`]):
|
157
|
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
|
158
|
+
specifically the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant,
|
159
|
+
with an additional added projection layer that is initialized with a diagonal matrix with the `hidden_size`
|
160
|
+
as its dimension.
|
161
|
+
text_encoder_2 ([`CLIPTextModelWithProjection`]):
|
162
|
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
|
163
|
+
specifically the
|
164
|
+
[laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
|
165
|
+
variant.
|
166
|
+
text_encoder_3 ([`T5EncoderModel`]):
|
167
|
+
Frozen text-encoder. Stable Diffusion 3 uses
|
168
|
+
[T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), specifically the
|
169
|
+
[t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
|
170
|
+
tokenizer (`CLIPTokenizer`):
|
171
|
+
Tokenizer of class
|
172
|
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
173
|
+
tokenizer_2 (`CLIPTokenizer`):
|
174
|
+
Second Tokenizer of class
|
175
|
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
176
|
+
tokenizer_3 (`T5TokenizerFast`):
|
177
|
+
Tokenizer of class
|
178
|
+
[T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
|
179
|
+
image_encoder (`PreTrainedModel`, *optional*):
|
180
|
+
Pre-trained Vision Model for IP Adapter.
|
181
|
+
feature_extractor (`BaseImageProcessor`, *optional*):
|
182
|
+
Image processor for IP Adapter.
|
183
|
+
"""
|
184
|
+
|
185
|
+
model_cpu_offload_seq = "text_encoder->text_encoder_2->text_encoder_3->image_encoder->transformer->vae"
|
186
|
+
_optional_components = ["image_encoder", "feature_extractor"]
|
187
|
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds", "negative_pooled_prompt_embeds"]
|
188
|
+
|
189
|
+
def __init__(
|
190
|
+
self,
|
191
|
+
transformer: SD3Transformer2DModel,
|
192
|
+
scheduler: FlowMatchEulerDiscreteScheduler,
|
193
|
+
vae: AutoencoderKL,
|
194
|
+
text_encoder: CLIPTextModelWithProjection,
|
195
|
+
tokenizer: CLIPTokenizer,
|
196
|
+
text_encoder_2: CLIPTextModelWithProjection,
|
197
|
+
tokenizer_2: CLIPTokenizer,
|
198
|
+
text_encoder_3: T5EncoderModel,
|
199
|
+
tokenizer_3: T5TokenizerFast,
|
200
|
+
image_encoder: PreTrainedModel = None,
|
201
|
+
feature_extractor: BaseImageProcessor = None,
|
202
|
+
):
|
203
|
+
super().__init__()
|
204
|
+
|
205
|
+
self.register_modules(
|
206
|
+
vae=vae,
|
207
|
+
text_encoder=text_encoder,
|
208
|
+
text_encoder_2=text_encoder_2,
|
209
|
+
text_encoder_3=text_encoder_3,
|
210
|
+
tokenizer=tokenizer,
|
211
|
+
tokenizer_2=tokenizer_2,
|
212
|
+
tokenizer_3=tokenizer_3,
|
213
|
+
transformer=transformer,
|
214
|
+
scheduler=scheduler,
|
215
|
+
image_encoder=image_encoder,
|
216
|
+
feature_extractor=feature_extractor,
|
217
|
+
)
|
218
|
+
self.vae_scale_factor = (
|
219
|
+
2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
|
220
|
+
)
|
221
|
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
222
|
+
self.tokenizer_max_length = (
|
223
|
+
self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
|
224
|
+
)
|
225
|
+
self.default_sample_size = (
|
226
|
+
self.transformer.config.sample_size
|
227
|
+
if hasattr(self, "transformer") and self.transformer is not None
|
228
|
+
else 128
|
229
|
+
)
|
230
|
+
self.patch_size = (
|
231
|
+
self.transformer.config.patch_size if hasattr(self, "transformer") and self.transformer is not None else 2
|
232
|
+
)
|
233
|
+
|
234
|
+
def _get_t5_prompt_embeds(
|
235
|
+
self,
|
236
|
+
prompt: Union[str, List[str]] = None,
|
237
|
+
num_images_per_prompt: int = 1,
|
238
|
+
max_sequence_length: int = 256,
|
239
|
+
device: Optional[torch.device] = None,
|
240
|
+
dtype: Optional[torch.dtype] = None,
|
241
|
+
):
|
242
|
+
device = device or self._execution_device
|
243
|
+
dtype = dtype or self.text_encoder.dtype
|
244
|
+
|
245
|
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
246
|
+
batch_size = len(prompt)
|
247
|
+
|
248
|
+
if self.text_encoder_3 is None:
|
249
|
+
return torch.zeros(
|
250
|
+
(
|
251
|
+
batch_size * num_images_per_prompt,
|
252
|
+
self.tokenizer_max_length,
|
253
|
+
self.transformer.config.joint_attention_dim,
|
254
|
+
),
|
255
|
+
device=device,
|
256
|
+
dtype=dtype,
|
257
|
+
)
|
258
|
+
|
259
|
+
text_inputs = self.tokenizer_3(
|
260
|
+
prompt,
|
261
|
+
padding="max_length",
|
262
|
+
max_length=max_sequence_length,
|
263
|
+
truncation=True,
|
264
|
+
add_special_tokens=True,
|
265
|
+
return_tensors="pt",
|
266
|
+
)
|
267
|
+
text_input_ids = text_inputs.input_ids
|
268
|
+
untruncated_ids = self.tokenizer_3(prompt, padding="longest", return_tensors="pt").input_ids
|
269
|
+
|
270
|
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
271
|
+
removed_text = self.tokenizer_3.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
|
272
|
+
logger.warning(
|
273
|
+
"The following part of your input was truncated because `max_sequence_length` is set to "
|
274
|
+
f" {max_sequence_length} tokens: {removed_text}"
|
275
|
+
)
|
276
|
+
|
277
|
+
prompt_embeds = self.text_encoder_3(text_input_ids.to(device))[0]
|
278
|
+
|
279
|
+
dtype = self.text_encoder_3.dtype
|
280
|
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
281
|
+
|
282
|
+
_, seq_len, _ = prompt_embeds.shape
|
283
|
+
|
284
|
+
# duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
|
285
|
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
286
|
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
287
|
+
|
288
|
+
return prompt_embeds
|
289
|
+
|
290
|
+
def _get_clip_prompt_embeds(
|
291
|
+
self,
|
292
|
+
prompt: Union[str, List[str]],
|
293
|
+
num_images_per_prompt: int = 1,
|
294
|
+
device: Optional[torch.device] = None,
|
295
|
+
clip_skip: Optional[int] = None,
|
296
|
+
clip_model_index: int = 0,
|
297
|
+
):
|
298
|
+
device = device or self._execution_device
|
299
|
+
|
300
|
+
clip_tokenizers = [self.tokenizer, self.tokenizer_2]
|
301
|
+
clip_text_encoders = [self.text_encoder, self.text_encoder_2]
|
302
|
+
|
303
|
+
tokenizer = clip_tokenizers[clip_model_index]
|
304
|
+
text_encoder = clip_text_encoders[clip_model_index]
|
305
|
+
|
306
|
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
307
|
+
batch_size = len(prompt)
|
308
|
+
|
309
|
+
text_inputs = tokenizer(
|
310
|
+
prompt,
|
311
|
+
padding="max_length",
|
312
|
+
max_length=self.tokenizer_max_length,
|
313
|
+
truncation=True,
|
314
|
+
return_tensors="pt",
|
315
|
+
)
|
316
|
+
|
317
|
+
text_input_ids = text_inputs.input_ids
|
318
|
+
untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
319
|
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
320
|
+
removed_text = tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
|
321
|
+
logger.warning(
|
322
|
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
323
|
+
f" {self.tokenizer_max_length} tokens: {removed_text}"
|
324
|
+
)
|
325
|
+
prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
|
326
|
+
pooled_prompt_embeds = prompt_embeds[0]
|
327
|
+
|
328
|
+
if clip_skip is None:
|
329
|
+
prompt_embeds = prompt_embeds.hidden_states[-2]
|
330
|
+
else:
|
331
|
+
prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
|
332
|
+
|
333
|
+
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
|
334
|
+
|
335
|
+
_, seq_len, _ = prompt_embeds.shape
|
336
|
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
337
|
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
338
|
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
339
|
+
|
340
|
+
pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
341
|
+
pooled_prompt_embeds = pooled_prompt_embeds.view(batch_size * num_images_per_prompt, -1)
|
342
|
+
|
343
|
+
return prompt_embeds, pooled_prompt_embeds
|
344
|
+
|
345
|
+
def encode_prompt(
|
346
|
+
self,
|
347
|
+
prompt: Union[str, List[str]],
|
348
|
+
prompt_2: Union[str, List[str]],
|
349
|
+
prompt_3: Union[str, List[str]],
|
350
|
+
device: Optional[torch.device] = None,
|
351
|
+
num_images_per_prompt: int = 1,
|
352
|
+
do_classifier_free_guidance: bool = True,
|
353
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
354
|
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
355
|
+
negative_prompt_3: Optional[Union[str, List[str]]] = None,
|
356
|
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
357
|
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
358
|
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
359
|
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
360
|
+
clip_skip: Optional[int] = None,
|
361
|
+
max_sequence_length: int = 256,
|
362
|
+
lora_scale: Optional[float] = None,
|
363
|
+
):
|
364
|
+
r"""
|
365
|
+
|
366
|
+
Args:
|
367
|
+
prompt (`str` or `List[str]`, *optional*):
|
368
|
+
prompt to be encoded
|
369
|
+
prompt_2 (`str` or `List[str]`, *optional*):
|
370
|
+
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
371
|
+
used in all text-encoders
|
372
|
+
prompt_3 (`str` or `List[str]`, *optional*):
|
373
|
+
The prompt or prompts to be sent to the `tokenizer_3` and `text_encoder_3`. If not defined, `prompt` is
|
374
|
+
used in all text-encoders
|
375
|
+
device: (`torch.device`):
|
376
|
+
torch device
|
377
|
+
num_images_per_prompt (`int`):
|
378
|
+
number of images that should be generated per prompt
|
379
|
+
do_classifier_free_guidance (`bool`):
|
380
|
+
whether to use classifier free guidance or not
|
381
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
382
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
383
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
384
|
+
less than `1`).
|
385
|
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
386
|
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
387
|
+
`text_encoder_2`. If not defined, `negative_prompt` is used in all the text-encoders.
|
388
|
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
389
|
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_3` and
|
390
|
+
`text_encoder_3`. If not defined, `negative_prompt` is used in both text-encoders
|
391
|
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
392
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
393
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
394
|
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
395
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
396
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
397
|
+
argument.
|
398
|
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
399
|
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
400
|
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
401
|
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
402
|
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
403
|
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
404
|
+
input argument.
|
405
|
+
clip_skip (`int`, *optional*):
|
406
|
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
407
|
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
408
|
+
lora_scale (`float`, *optional*):
|
409
|
+
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
410
|
+
"""
|
411
|
+
device = device or self._execution_device
|
412
|
+
|
413
|
+
# set lora scale so that monkey patched LoRA
|
414
|
+
# function of text encoder can correctly access it
|
415
|
+
if lora_scale is not None and isinstance(self, SD3LoraLoaderMixin):
|
416
|
+
self._lora_scale = lora_scale
|
417
|
+
|
418
|
+
# dynamically adjust the LoRA scale
|
419
|
+
if self.text_encoder is not None and USE_PEFT_BACKEND:
|
420
|
+
scale_lora_layers(self.text_encoder, lora_scale)
|
421
|
+
if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
|
422
|
+
scale_lora_layers(self.text_encoder_2, lora_scale)
|
423
|
+
|
424
|
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
425
|
+
if prompt is not None:
|
426
|
+
batch_size = len(prompt)
|
427
|
+
else:
|
428
|
+
batch_size = prompt_embeds.shape[0]
|
429
|
+
|
430
|
+
if prompt_embeds is None:
|
431
|
+
prompt_2 = prompt_2 or prompt
|
432
|
+
prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
|
433
|
+
|
434
|
+
prompt_3 = prompt_3 or prompt
|
435
|
+
prompt_3 = [prompt_3] if isinstance(prompt_3, str) else prompt_3
|
436
|
+
|
437
|
+
prompt_embed, pooled_prompt_embed = self._get_clip_prompt_embeds(
|
438
|
+
prompt=prompt,
|
439
|
+
device=device,
|
440
|
+
num_images_per_prompt=num_images_per_prompt,
|
441
|
+
clip_skip=clip_skip,
|
442
|
+
clip_model_index=0,
|
443
|
+
)
|
444
|
+
prompt_2_embed, pooled_prompt_2_embed = self._get_clip_prompt_embeds(
|
445
|
+
prompt=prompt_2,
|
446
|
+
device=device,
|
447
|
+
num_images_per_prompt=num_images_per_prompt,
|
448
|
+
clip_skip=clip_skip,
|
449
|
+
clip_model_index=1,
|
450
|
+
)
|
451
|
+
clip_prompt_embeds = torch.cat([prompt_embed, prompt_2_embed], dim=-1)
|
452
|
+
|
453
|
+
t5_prompt_embed = self._get_t5_prompt_embeds(
|
454
|
+
prompt=prompt_3,
|
455
|
+
num_images_per_prompt=num_images_per_prompt,
|
456
|
+
max_sequence_length=max_sequence_length,
|
457
|
+
device=device,
|
458
|
+
)
|
459
|
+
|
460
|
+
clip_prompt_embeds = torch.nn.functional.pad(
|
461
|
+
clip_prompt_embeds, (0, t5_prompt_embed.shape[-1] - clip_prompt_embeds.shape[-1])
|
462
|
+
)
|
463
|
+
|
464
|
+
prompt_embeds = torch.cat([clip_prompt_embeds, t5_prompt_embed], dim=-2)
|
465
|
+
pooled_prompt_embeds = torch.cat([pooled_prompt_embed, pooled_prompt_2_embed], dim=-1)
|
466
|
+
|
467
|
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
468
|
+
negative_prompt = negative_prompt or ""
|
469
|
+
negative_prompt_2 = negative_prompt_2 or negative_prompt
|
470
|
+
negative_prompt_3 = negative_prompt_3 or negative_prompt
|
471
|
+
|
472
|
+
# normalize str to list
|
473
|
+
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
474
|
+
negative_prompt_2 = (
|
475
|
+
batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
|
476
|
+
)
|
477
|
+
negative_prompt_3 = (
|
478
|
+
batch_size * [negative_prompt_3] if isinstance(negative_prompt_3, str) else negative_prompt_3
|
479
|
+
)
|
480
|
+
|
481
|
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
482
|
+
raise TypeError(
|
483
|
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
484
|
+
f" {type(prompt)}."
|
485
|
+
)
|
486
|
+
elif batch_size != len(negative_prompt):
|
487
|
+
raise ValueError(
|
488
|
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
489
|
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
490
|
+
" the batch size of `prompt`."
|
491
|
+
)
|
492
|
+
|
493
|
+
negative_prompt_embed, negative_pooled_prompt_embed = self._get_clip_prompt_embeds(
|
494
|
+
negative_prompt,
|
495
|
+
device=device,
|
496
|
+
num_images_per_prompt=num_images_per_prompt,
|
497
|
+
clip_skip=None,
|
498
|
+
clip_model_index=0,
|
499
|
+
)
|
500
|
+
negative_prompt_2_embed, negative_pooled_prompt_2_embed = self._get_clip_prompt_embeds(
|
501
|
+
negative_prompt_2,
|
502
|
+
device=device,
|
503
|
+
num_images_per_prompt=num_images_per_prompt,
|
504
|
+
clip_skip=None,
|
505
|
+
clip_model_index=1,
|
506
|
+
)
|
507
|
+
negative_clip_prompt_embeds = torch.cat([negative_prompt_embed, negative_prompt_2_embed], dim=-1)
|
508
|
+
|
509
|
+
t5_negative_prompt_embed = self._get_t5_prompt_embeds(
|
510
|
+
prompt=negative_prompt_3,
|
511
|
+
num_images_per_prompt=num_images_per_prompt,
|
512
|
+
max_sequence_length=max_sequence_length,
|
513
|
+
device=device,
|
514
|
+
)
|
515
|
+
|
516
|
+
negative_clip_prompt_embeds = torch.nn.functional.pad(
|
517
|
+
negative_clip_prompt_embeds,
|
518
|
+
(0, t5_negative_prompt_embed.shape[-1] - negative_clip_prompt_embeds.shape[-1]),
|
519
|
+
)
|
520
|
+
|
521
|
+
negative_prompt_embeds = torch.cat([negative_clip_prompt_embeds, t5_negative_prompt_embed], dim=-2)
|
522
|
+
negative_pooled_prompt_embeds = torch.cat(
|
523
|
+
[negative_pooled_prompt_embed, negative_pooled_prompt_2_embed], dim=-1
|
524
|
+
)
|
525
|
+
|
526
|
+
if self.text_encoder is not None:
|
527
|
+
if isinstance(self, SD3LoraLoaderMixin) and USE_PEFT_BACKEND:
|
528
|
+
# Retrieve the original scale by scaling back the LoRA layers
|
529
|
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
530
|
+
|
531
|
+
if self.text_encoder_2 is not None:
|
532
|
+
if isinstance(self, SD3LoraLoaderMixin) and USE_PEFT_BACKEND:
|
533
|
+
# Retrieve the original scale by scaling back the LoRA layers
|
534
|
+
unscale_lora_layers(self.text_encoder_2, lora_scale)
|
535
|
+
|
536
|
+
return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
|
537
|
+
|
538
|
+
def check_inputs(
|
539
|
+
self,
|
540
|
+
prompt,
|
541
|
+
prompt_2,
|
542
|
+
prompt_3,
|
543
|
+
height,
|
544
|
+
width,
|
545
|
+
negative_prompt=None,
|
546
|
+
negative_prompt_2=None,
|
547
|
+
negative_prompt_3=None,
|
548
|
+
prompt_embeds=None,
|
549
|
+
negative_prompt_embeds=None,
|
550
|
+
pooled_prompt_embeds=None,
|
551
|
+
negative_pooled_prompt_embeds=None,
|
552
|
+
callback_on_step_end_tensor_inputs=None,
|
553
|
+
max_sequence_length=None,
|
554
|
+
):
|
555
|
+
if (
|
556
|
+
height % (self.vae_scale_factor * self.patch_size) != 0
|
557
|
+
or width % (self.vae_scale_factor * self.patch_size) != 0
|
558
|
+
):
|
559
|
+
raise ValueError(
|
560
|
+
f"`height` and `width` have to be divisible by {self.vae_scale_factor * self.patch_size} but are {height} and {width}."
|
561
|
+
f"You can use height {height - height % (self.vae_scale_factor * self.patch_size)} and width {width - width % (self.vae_scale_factor * self.patch_size)}."
|
562
|
+
)
|
563
|
+
|
564
|
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
565
|
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
566
|
+
):
|
567
|
+
raise ValueError(
|
568
|
+
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]}"
|
569
|
+
)
|
570
|
+
|
571
|
+
if prompt is not None and prompt_embeds is not None:
|
572
|
+
raise ValueError(
|
573
|
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
574
|
+
" only forward one of the two."
|
575
|
+
)
|
576
|
+
elif prompt_2 is not None and prompt_embeds is not None:
|
577
|
+
raise ValueError(
|
578
|
+
f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
579
|
+
" only forward one of the two."
|
580
|
+
)
|
581
|
+
elif prompt_3 is not None and prompt_embeds is not None:
|
582
|
+
raise ValueError(
|
583
|
+
f"Cannot forward both `prompt_3`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
584
|
+
" only forward one of the two."
|
585
|
+
)
|
586
|
+
elif prompt is None and prompt_embeds is None:
|
587
|
+
raise ValueError(
|
588
|
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
589
|
+
)
|
590
|
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
591
|
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
592
|
+
elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
|
593
|
+
raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
|
594
|
+
elif prompt_3 is not None and (not isinstance(prompt_3, str) and not isinstance(prompt_3, list)):
|
595
|
+
raise ValueError(f"`prompt_3` has to be of type `str` or `list` but is {type(prompt_3)}")
|
596
|
+
|
597
|
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
598
|
+
raise ValueError(
|
599
|
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
600
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
601
|
+
)
|
602
|
+
elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
|
603
|
+
raise ValueError(
|
604
|
+
f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
|
605
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
606
|
+
)
|
607
|
+
elif negative_prompt_3 is not None and negative_prompt_embeds is not None:
|
608
|
+
raise ValueError(
|
609
|
+
f"Cannot forward both `negative_prompt_3`: {negative_prompt_3} and `negative_prompt_embeds`:"
|
610
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
611
|
+
)
|
612
|
+
|
613
|
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
614
|
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
615
|
+
raise ValueError(
|
616
|
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
617
|
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
618
|
+
f" {negative_prompt_embeds.shape}."
|
619
|
+
)
|
620
|
+
|
621
|
+
if prompt_embeds is not None and pooled_prompt_embeds is None:
|
622
|
+
raise ValueError(
|
623
|
+
"If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
|
624
|
+
)
|
625
|
+
|
626
|
+
if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
|
627
|
+
raise ValueError(
|
628
|
+
"If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
|
629
|
+
)
|
630
|
+
|
631
|
+
if max_sequence_length is not None and max_sequence_length > 512:
|
632
|
+
raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
|
633
|
+
|
634
|
+
def prepare_latents(
|
635
|
+
self,
|
636
|
+
batch_size,
|
637
|
+
num_channels_latents,
|
638
|
+
height,
|
639
|
+
width,
|
640
|
+
dtype,
|
641
|
+
device,
|
642
|
+
generator,
|
643
|
+
latents=None,
|
644
|
+
):
|
645
|
+
if latents is not None:
|
646
|
+
return latents.to(device=device, dtype=dtype)
|
647
|
+
|
648
|
+
shape = (
|
649
|
+
batch_size,
|
650
|
+
num_channels_latents,
|
651
|
+
int(height) // self.vae_scale_factor,
|
652
|
+
int(width) // self.vae_scale_factor,
|
653
|
+
)
|
654
|
+
|
655
|
+
if isinstance(generator, list) and len(generator) != batch_size:
|
656
|
+
raise ValueError(
|
657
|
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
658
|
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
659
|
+
)
|
660
|
+
|
661
|
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
662
|
+
|
663
|
+
return latents
|
664
|
+
|
665
|
+
@property
|
666
|
+
def guidance_scale(self):
|
667
|
+
return self._guidance_scale
|
668
|
+
|
669
|
+
@property
|
670
|
+
def skip_guidance_layers(self):
|
671
|
+
return self._skip_guidance_layers
|
672
|
+
|
673
|
+
@property
|
674
|
+
def clip_skip(self):
|
675
|
+
return self._clip_skip
|
676
|
+
|
677
|
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
678
|
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
679
|
+
# corresponds to doing no classifier free guidance.
|
680
|
+
@property
|
681
|
+
def do_classifier_free_guidance(self):
|
682
|
+
return self._guidance_scale > 1
|
683
|
+
|
684
|
+
@property
|
685
|
+
def joint_attention_kwargs(self):
|
686
|
+
return self._joint_attention_kwargs
|
687
|
+
|
688
|
+
@property
|
689
|
+
def num_timesteps(self):
|
690
|
+
return self._num_timesteps
|
691
|
+
|
692
|
+
@property
|
693
|
+
def interrupt(self):
|
694
|
+
return self._interrupt
|
695
|
+
|
696
|
+
# Adapted from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_image
|
697
|
+
def encode_image(self, image: PipelineImageInput, device: torch.device) -> torch.Tensor:
|
698
|
+
"""Encodes the given image into a feature representation using a pre-trained image encoder.
|
699
|
+
|
700
|
+
Args:
|
701
|
+
image (`PipelineImageInput`):
|
702
|
+
Input image to be encoded.
|
703
|
+
device: (`torch.device`):
|
704
|
+
Torch device.
|
705
|
+
|
706
|
+
Returns:
|
707
|
+
`torch.Tensor`: The encoded image feature representation.
|
708
|
+
"""
|
709
|
+
if not isinstance(image, torch.Tensor):
|
710
|
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
711
|
+
|
712
|
+
image = image.to(device=device, dtype=self.dtype)
|
713
|
+
|
714
|
+
return self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
|
715
|
+
|
716
|
+
# Adapted from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.prepare_ip_adapter_image_embeds
|
717
|
+
def prepare_ip_adapter_image_embeds(
|
718
|
+
self,
|
719
|
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
720
|
+
ip_adapter_image_embeds: Optional[torch.Tensor] = None,
|
721
|
+
device: Optional[torch.device] = None,
|
722
|
+
num_images_per_prompt: int = 1,
|
723
|
+
do_classifier_free_guidance: bool = True,
|
724
|
+
) -> torch.Tensor:
|
725
|
+
"""Prepares image embeddings for use in the IP-Adapter.
|
726
|
+
|
727
|
+
Either `ip_adapter_image` or `ip_adapter_image_embeds` must be passed.
|
728
|
+
|
729
|
+
Args:
|
730
|
+
ip_adapter_image (`PipelineImageInput`, *optional*):
|
731
|
+
The input image to extract features from for IP-Adapter.
|
732
|
+
ip_adapter_image_embeds (`torch.Tensor`, *optional*):
|
733
|
+
Precomputed image embeddings.
|
734
|
+
device: (`torch.device`, *optional*):
|
735
|
+
Torch device.
|
736
|
+
num_images_per_prompt (`int`, defaults to 1):
|
737
|
+
Number of images that should be generated per prompt.
|
738
|
+
do_classifier_free_guidance (`bool`, defaults to True):
|
739
|
+
Whether to use classifier free guidance or not.
|
740
|
+
"""
|
741
|
+
device = device or self._execution_device
|
742
|
+
|
743
|
+
if ip_adapter_image_embeds is not None:
|
744
|
+
if do_classifier_free_guidance:
|
745
|
+
single_negative_image_embeds, single_image_embeds = ip_adapter_image_embeds.chunk(2)
|
746
|
+
else:
|
747
|
+
single_image_embeds = ip_adapter_image_embeds
|
748
|
+
elif ip_adapter_image is not None:
|
749
|
+
single_image_embeds = self.encode_image(ip_adapter_image, device)
|
750
|
+
if do_classifier_free_guidance:
|
751
|
+
single_negative_image_embeds = torch.zeros_like(single_image_embeds)
|
752
|
+
else:
|
753
|
+
raise ValueError("Neither `ip_adapter_image_embeds` or `ip_adapter_image_embeds` were provided.")
|
754
|
+
|
755
|
+
image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
|
756
|
+
|
757
|
+
if do_classifier_free_guidance:
|
758
|
+
negative_image_embeds = torch.cat([single_negative_image_embeds] * num_images_per_prompt, dim=0)
|
759
|
+
image_embeds = torch.cat([negative_image_embeds, image_embeds], dim=0)
|
760
|
+
|
761
|
+
return image_embeds.to(device=device)
|
762
|
+
|
763
|
+
def enable_sequential_cpu_offload(self, *args, **kwargs):
|
764
|
+
if self.image_encoder is not None and "image_encoder" not in self._exclude_from_cpu_offload:
|
765
|
+
logger.warning(
|
766
|
+
"`pipe.enable_sequential_cpu_offload()` might fail for `image_encoder` if it uses "
|
767
|
+
"`torch.nn.MultiheadAttention`. You can exclude `image_encoder` from CPU offloading by calling "
|
768
|
+
"`pipe._exclude_from_cpu_offload.append('image_encoder')` before `pipe.enable_sequential_cpu_offload()`."
|
769
|
+
)
|
770
|
+
|
771
|
+
super().enable_sequential_cpu_offload(*args, **kwargs)
|
772
|
+
|
773
|
+
@torch.no_grad()
|
774
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
775
|
+
def __call__(
|
776
|
+
self,
|
777
|
+
prompt: Union[str, List[str]] = None,
|
778
|
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
779
|
+
prompt_3: Optional[Union[str, List[str]]] = None,
|
780
|
+
height: Optional[int] = None,
|
781
|
+
width: Optional[int] = None,
|
782
|
+
num_inference_steps: int = 28,
|
783
|
+
sigmas: Optional[List[float]] = None,
|
784
|
+
guidance_scale: float = 7.0,
|
785
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
786
|
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
787
|
+
negative_prompt_3: Optional[Union[str, List[str]]] = None,
|
788
|
+
num_images_per_prompt: Optional[int] = 1,
|
789
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
790
|
+
latents: Optional[torch.FloatTensor] = None,
|
791
|
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
792
|
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
793
|
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
794
|
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
795
|
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
796
|
+
ip_adapter_image_embeds: Optional[torch.Tensor] = None,
|
797
|
+
output_type: Optional[str] = "pil",
|
798
|
+
return_dict: bool = True,
|
799
|
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
800
|
+
clip_skip: Optional[int] = None,
|
801
|
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
802
|
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
803
|
+
max_sequence_length: int = 256,
|
804
|
+
skip_guidance_layers: List[int] = None,
|
805
|
+
skip_layer_guidance_scale: float = 2.8,
|
806
|
+
skip_layer_guidance_stop: float = 0.2,
|
807
|
+
skip_layer_guidance_start: float = 0.01,
|
808
|
+
mu: Optional[float] = None,
|
809
|
+
):
|
810
|
+
r"""
|
811
|
+
Function invoked when calling the pipeline for generation.
|
812
|
+
|
813
|
+
Args:
|
814
|
+
prompt (`str` or `List[str]`, *optional*):
|
815
|
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
816
|
+
instead.
|
817
|
+
prompt_2 (`str` or `List[str]`, *optional*):
|
818
|
+
The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
819
|
+
will be used instead
|
820
|
+
prompt_3 (`str` or `List[str]`, *optional*):
|
821
|
+
The prompt or prompts to be sent to `tokenizer_3` and `text_encoder_3`. If not defined, `prompt` is
|
822
|
+
will be used instead
|
823
|
+
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
824
|
+
The height in pixels of the generated image. This is set to 1024 by default for the best results.
|
825
|
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
826
|
+
The width in pixels of the generated image. This is set to 1024 by default for the best results.
|
827
|
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
828
|
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
829
|
+
expense of slower inference.
|
830
|
+
sigmas (`List[float]`, *optional*):
|
831
|
+
Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
|
832
|
+
their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
|
833
|
+
will be used.
|
834
|
+
guidance_scale (`float`, *optional*, defaults to 7.0):
|
835
|
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
836
|
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
837
|
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
838
|
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
839
|
+
usually at the expense of lower image quality.
|
840
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
841
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
842
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
843
|
+
less than `1`).
|
844
|
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
845
|
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
846
|
+
`text_encoder_2`. If not defined, `negative_prompt` is used instead
|
847
|
+
negative_prompt_3 (`str` or `List[str]`, *optional*):
|
848
|
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_3` and
|
849
|
+
`text_encoder_3`. If not defined, `negative_prompt` is used instead
|
850
|
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
851
|
+
The number of images to generate per prompt.
|
852
|
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
853
|
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
854
|
+
to make generation deterministic.
|
855
|
+
latents (`torch.FloatTensor`, *optional*):
|
856
|
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
857
|
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
858
|
+
tensor will ge generated by sampling using the supplied random `generator`.
|
859
|
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
860
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
861
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
862
|
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
863
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
864
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
865
|
+
argument.
|
866
|
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
867
|
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
868
|
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
869
|
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
870
|
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
871
|
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
872
|
+
input argument.
|
873
|
+
ip_adapter_image (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
|
874
|
+
ip_adapter_image_embeds (`torch.Tensor`, *optional*):
|
875
|
+
Pre-generated image embeddings for IP-Adapter. Should be a tensor of shape `(batch_size, num_images,
|
876
|
+
emb_dim)`. It should contain the negative image embedding if `do_classifier_free_guidance` is set to
|
877
|
+
`True`. If not provided, embeddings are computed from the `ip_adapter_image` input argument.
|
878
|
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
879
|
+
The output format of the generate image. Choose between
|
880
|
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
881
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
882
|
+
Whether or not to return a [`~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput`] instead of
|
883
|
+
a plain tuple.
|
884
|
+
joint_attention_kwargs (`dict`, *optional*):
|
885
|
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
886
|
+
`self.processor` in
|
887
|
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
888
|
+
callback_on_step_end (`Callable`, *optional*):
|
889
|
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
890
|
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
891
|
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
892
|
+
`callback_on_step_end_tensor_inputs`.
|
893
|
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
894
|
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
895
|
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
896
|
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
897
|
+
max_sequence_length (`int` defaults to 256): Maximum sequence length to use with the `prompt`.
|
898
|
+
skip_guidance_layers (`List[int]`, *optional*):
|
899
|
+
A list of integers that specify layers to skip during guidance. If not provided, all layers will be
|
900
|
+
used for guidance. If provided, the guidance will only be applied to the layers specified in the list.
|
901
|
+
Recommended value by StabiltyAI for Stable Diffusion 3.5 Medium is [7, 8, 9].
|
902
|
+
skip_layer_guidance_scale (`int`, *optional*): The scale of the guidance for the layers specified in
|
903
|
+
`skip_guidance_layers`. The guidance will be applied to the layers specified in `skip_guidance_layers`
|
904
|
+
with a scale of `skip_layer_guidance_scale`. The guidance will be applied to the rest of the layers
|
905
|
+
with a scale of `1`.
|
906
|
+
skip_layer_guidance_stop (`int`, *optional*): The step at which the guidance for the layers specified in
|
907
|
+
`skip_guidance_layers` will stop. The guidance will be applied to the layers specified in
|
908
|
+
`skip_guidance_layers` until the fraction specified in `skip_layer_guidance_stop`. Recommended value by
|
909
|
+
StabiltyAI for Stable Diffusion 3.5 Medium is 0.2.
|
910
|
+
skip_layer_guidance_start (`int`, *optional*): The step at which the guidance for the layers specified in
|
911
|
+
`skip_guidance_layers` will start. The guidance will be applied to the layers specified in
|
912
|
+
`skip_guidance_layers` from the fraction specified in `skip_layer_guidance_start`. Recommended value by
|
913
|
+
StabiltyAI for Stable Diffusion 3.5 Medium is 0.01.
|
914
|
+
mu (`float`, *optional*): `mu` value used for `dynamic_shifting`.
|
915
|
+
|
916
|
+
Examples:
|
917
|
+
|
918
|
+
Returns:
|
919
|
+
[`~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput`] or `tuple`:
|
920
|
+
[`~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput`] if `return_dict` is True, otherwise a
|
921
|
+
`tuple`. When returning a tuple, the first element is a list with the generated images.
|
922
|
+
"""
|
923
|
+
|
924
|
+
height = height or self.default_sample_size * self.vae_scale_factor
|
925
|
+
width = width or self.default_sample_size * self.vae_scale_factor
|
926
|
+
|
927
|
+
# 1. Check inputs. Raise error if not correct
|
928
|
+
self.check_inputs(
|
929
|
+
prompt,
|
930
|
+
prompt_2,
|
931
|
+
prompt_3,
|
932
|
+
height,
|
933
|
+
width,
|
934
|
+
negative_prompt=negative_prompt,
|
935
|
+
negative_prompt_2=negative_prompt_2,
|
936
|
+
negative_prompt_3=negative_prompt_3,
|
937
|
+
prompt_embeds=prompt_embeds,
|
938
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
939
|
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
940
|
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
941
|
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
942
|
+
max_sequence_length=max_sequence_length,
|
943
|
+
)
|
944
|
+
|
945
|
+
self._guidance_scale = guidance_scale
|
946
|
+
self._skip_layer_guidance_scale = skip_layer_guidance_scale
|
947
|
+
self._clip_skip = clip_skip
|
948
|
+
self._joint_attention_kwargs = joint_attention_kwargs
|
949
|
+
self._interrupt = False
|
950
|
+
|
951
|
+
# 2. Define call parameters
|
952
|
+
if prompt is not None and isinstance(prompt, str):
|
953
|
+
batch_size = 1
|
954
|
+
elif prompt is not None and isinstance(prompt, list):
|
955
|
+
batch_size = len(prompt)
|
956
|
+
else:
|
957
|
+
batch_size = prompt_embeds.shape[0]
|
958
|
+
|
959
|
+
device = self._execution_device
|
960
|
+
|
961
|
+
lora_scale = (
|
962
|
+
self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
|
963
|
+
)
|
964
|
+
(
|
965
|
+
prompt_embeds,
|
966
|
+
negative_prompt_embeds,
|
967
|
+
pooled_prompt_embeds,
|
968
|
+
negative_pooled_prompt_embeds,
|
969
|
+
) = self.encode_prompt(
|
970
|
+
prompt=prompt,
|
971
|
+
prompt_2=prompt_2,
|
972
|
+
prompt_3=prompt_3,
|
973
|
+
negative_prompt=negative_prompt,
|
974
|
+
negative_prompt_2=negative_prompt_2,
|
975
|
+
negative_prompt_3=negative_prompt_3,
|
976
|
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
977
|
+
prompt_embeds=prompt_embeds,
|
978
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
979
|
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
980
|
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
981
|
+
device=device,
|
982
|
+
clip_skip=self.clip_skip,
|
983
|
+
num_images_per_prompt=num_images_per_prompt,
|
984
|
+
max_sequence_length=max_sequence_length,
|
985
|
+
lora_scale=lora_scale,
|
986
|
+
)
|
987
|
+
|
988
|
+
if self.do_classifier_free_guidance:
|
989
|
+
if skip_guidance_layers is not None:
|
990
|
+
original_prompt_embeds = prompt_embeds
|
991
|
+
original_pooled_prompt_embeds = pooled_prompt_embeds
|
992
|
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
993
|
+
pooled_prompt_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
|
994
|
+
|
995
|
+
# 4. Prepare latent variables
|
996
|
+
num_channels_latents = self.transformer.config.in_channels
|
997
|
+
latents = self.prepare_latents(
|
998
|
+
batch_size * num_images_per_prompt,
|
999
|
+
num_channels_latents,
|
1000
|
+
height,
|
1001
|
+
width,
|
1002
|
+
prompt_embeds.dtype,
|
1003
|
+
device,
|
1004
|
+
generator,
|
1005
|
+
latents,
|
1006
|
+
)
|
1007
|
+
|
1008
|
+
# 5. Prepare timesteps
|
1009
|
+
scheduler_kwargs = {}
|
1010
|
+
if self.scheduler.config.get("use_dynamic_shifting", None) and mu is None:
|
1011
|
+
_, _, height, width = latents.shape
|
1012
|
+
image_seq_len = (height // self.transformer.config.patch_size) * (
|
1013
|
+
width // self.transformer.config.patch_size
|
1014
|
+
)
|
1015
|
+
mu = calculate_shift(
|
1016
|
+
image_seq_len,
|
1017
|
+
self.scheduler.config.base_image_seq_len,
|
1018
|
+
self.scheduler.config.max_image_seq_len,
|
1019
|
+
self.scheduler.config.base_shift,
|
1020
|
+
self.scheduler.config.max_shift,
|
1021
|
+
)
|
1022
|
+
scheduler_kwargs["mu"] = mu
|
1023
|
+
elif mu is not None:
|
1024
|
+
scheduler_kwargs["mu"] = mu
|
1025
|
+
timesteps, num_inference_steps = retrieve_timesteps(
|
1026
|
+
self.scheduler,
|
1027
|
+
num_inference_steps,
|
1028
|
+
device,
|
1029
|
+
sigmas=sigmas,
|
1030
|
+
**scheduler_kwargs,
|
1031
|
+
)
|
1032
|
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
1033
|
+
self._num_timesteps = len(timesteps)
|
1034
|
+
|
1035
|
+
# 6. Prepare image embeddings
|
1036
|
+
if (ip_adapter_image is not None and self.is_ip_adapter_active) or ip_adapter_image_embeds is not None:
|
1037
|
+
ip_adapter_image_embeds = self.prepare_ip_adapter_image_embeds(
|
1038
|
+
ip_adapter_image,
|
1039
|
+
ip_adapter_image_embeds,
|
1040
|
+
device,
|
1041
|
+
batch_size * num_images_per_prompt,
|
1042
|
+
self.do_classifier_free_guidance,
|
1043
|
+
)
|
1044
|
+
|
1045
|
+
if self.joint_attention_kwargs is None:
|
1046
|
+
self._joint_attention_kwargs = {"ip_adapter_image_embeds": ip_adapter_image_embeds}
|
1047
|
+
else:
|
1048
|
+
self._joint_attention_kwargs.update(ip_adapter_image_embeds=ip_adapter_image_embeds)
|
1049
|
+
|
1050
|
+
# 7. Denoising loop
|
1051
|
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
1052
|
+
for i, t in enumerate(timesteps):
|
1053
|
+
if self.interrupt:
|
1054
|
+
continue
|
1055
|
+
|
1056
|
+
# expand the latents if we are doing classifier free guidance
|
1057
|
+
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
1058
|
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
1059
|
+
timestep = t.expand(latent_model_input.shape[0])
|
1060
|
+
|
1061
|
+
noise_pred = self.transformer(
|
1062
|
+
hidden_states=latent_model_input,
|
1063
|
+
timestep=timestep,
|
1064
|
+
encoder_hidden_states=prompt_embeds,
|
1065
|
+
pooled_projections=pooled_prompt_embeds,
|
1066
|
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
1067
|
+
return_dict=False,
|
1068
|
+
)[0]
|
1069
|
+
|
1070
|
+
# perform guidance
|
1071
|
+
if self.do_classifier_free_guidance:
|
1072
|
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
1073
|
+
noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
|
1074
|
+
should_skip_layers = (
|
1075
|
+
True
|
1076
|
+
if i > num_inference_steps * skip_layer_guidance_start
|
1077
|
+
and i < num_inference_steps * skip_layer_guidance_stop
|
1078
|
+
else False
|
1079
|
+
)
|
1080
|
+
if skip_guidance_layers is not None and should_skip_layers:
|
1081
|
+
timestep = t.expand(latents.shape[0])
|
1082
|
+
latent_model_input = latents
|
1083
|
+
noise_pred_skip_layers = self.transformer(
|
1084
|
+
hidden_states=latent_model_input,
|
1085
|
+
timestep=timestep,
|
1086
|
+
encoder_hidden_states=original_prompt_embeds,
|
1087
|
+
pooled_projections=original_pooled_prompt_embeds,
|
1088
|
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
1089
|
+
return_dict=False,
|
1090
|
+
skip_layers=skip_guidance_layers,
|
1091
|
+
)[0]
|
1092
|
+
noise_pred = (
|
1093
|
+
noise_pred + (noise_pred_text - noise_pred_skip_layers) * self._skip_layer_guidance_scale
|
1094
|
+
)
|
1095
|
+
|
1096
|
+
# compute the previous noisy sample x_t -> x_t-1
|
1097
|
+
latents_dtype = latents.dtype
|
1098
|
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
1099
|
+
|
1100
|
+
if latents.dtype != latents_dtype:
|
1101
|
+
if torch.backends.mps.is_available():
|
1102
|
+
# some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
|
1103
|
+
latents = latents.to(latents_dtype)
|
1104
|
+
|
1105
|
+
if callback_on_step_end is not None:
|
1106
|
+
callback_kwargs = {}
|
1107
|
+
for k in callback_on_step_end_tensor_inputs:
|
1108
|
+
callback_kwargs[k] = locals()[k]
|
1109
|
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
1110
|
+
|
1111
|
+
latents = callback_outputs.pop("latents", latents)
|
1112
|
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
1113
|
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
1114
|
+
negative_pooled_prompt_embeds = callback_outputs.pop(
|
1115
|
+
"negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
|
1116
|
+
)
|
1117
|
+
|
1118
|
+
# call the callback, if provided
|
1119
|
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
1120
|
+
progress_bar.update()
|
1121
|
+
|
1122
|
+
if XLA_AVAILABLE:
|
1123
|
+
xm.mark_step()
|
1124
|
+
|
1125
|
+
if output_type == "latent":
|
1126
|
+
image = latents
|
1127
|
+
|
1128
|
+
else:
|
1129
|
+
latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
|
1130
|
+
|
1131
|
+
image = self.vae.decode(latents, return_dict=False)[0]
|
1132
|
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
1133
|
+
|
1134
|
+
# Offload all models
|
1135
|
+
self.maybe_free_model_hooks()
|
1136
|
+
|
1137
|
+
if not return_dict:
|
1138
|
+
return (image,)
|
1139
|
+
|
1140
|
+
return StableDiffusion3PipelineOutput(images=image)
|