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,1250 @@
|
|
1
|
+
# Copyright 2024 Stability AI, Kwai-Kolors Team and 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
|
+
import inspect
|
15
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
16
|
+
|
17
|
+
import PIL.Image
|
18
|
+
import torch
|
19
|
+
from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
|
20
|
+
|
21
|
+
from ...callbacks import MultiPipelineCallbacks, PipelineCallback
|
22
|
+
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
23
|
+
from ...loaders import IPAdapterMixin, StableDiffusionXLLoraLoaderMixin
|
24
|
+
from ...models import AutoencoderKL, ImageProjection, UNet2DConditionModel
|
25
|
+
from ...models.attention_processor import AttnProcessor2_0, FusedAttnProcessor2_0, XFormersAttnProcessor
|
26
|
+
from ...schedulers import KarrasDiffusionSchedulers
|
27
|
+
from ...utils import is_torch_xla_available, logging, replace_example_docstring
|
28
|
+
from ...utils.torch_utils import randn_tensor
|
29
|
+
from ..pipeline_utils import DiffusionPipeline, StableDiffusionMixin
|
30
|
+
from .pipeline_output import KolorsPipelineOutput
|
31
|
+
from .text_encoder import ChatGLMModel
|
32
|
+
from .tokenizer import ChatGLMTokenizer
|
33
|
+
|
34
|
+
|
35
|
+
if is_torch_xla_available():
|
36
|
+
import torch_xla.core.xla_model as xm
|
37
|
+
|
38
|
+
XLA_AVAILABLE = True
|
39
|
+
else:
|
40
|
+
XLA_AVAILABLE = False
|
41
|
+
|
42
|
+
|
43
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
44
|
+
|
45
|
+
|
46
|
+
EXAMPLE_DOC_STRING = """
|
47
|
+
Examples:
|
48
|
+
```py
|
49
|
+
>>> import torch
|
50
|
+
>>> from diffusers import KolorsImg2ImgPipeline
|
51
|
+
>>> from diffusers.utils import load_image
|
52
|
+
|
53
|
+
>>> pipe = KolorsImg2ImgPipeline.from_pretrained(
|
54
|
+
... "Kwai-Kolors/Kolors-diffusers", variant="fp16", torch_dtype=torch.float16
|
55
|
+
... )
|
56
|
+
>>> pipe = pipe.to("cuda")
|
57
|
+
>>> url = (
|
58
|
+
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/kolors/bunny_source.png"
|
59
|
+
... )
|
60
|
+
|
61
|
+
|
62
|
+
>>> init_image = load_image(url)
|
63
|
+
>>> prompt = "high quality image of a capybara wearing sunglasses. In the background of the image there are trees, poles, grass and other objects. At the bottom of the object there is the road., 8k, highly detailed."
|
64
|
+
>>> image = pipe(prompt, image=init_image).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 KolorsImg2ImgPipeline(DiffusionPipeline, StableDiffusionMixin, StableDiffusionXLLoraLoaderMixin, IPAdapterMixin):
|
144
|
+
r"""
|
145
|
+
Pipeline for text-to-image generation using Kolors.
|
146
|
+
|
147
|
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
148
|
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
149
|
+
|
150
|
+
The pipeline also inherits the following loading methods:
|
151
|
+
- [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
152
|
+
- [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
153
|
+
- [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
|
154
|
+
|
155
|
+
Args:
|
156
|
+
vae ([`AutoencoderKL`]):
|
157
|
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
158
|
+
text_encoder ([`ChatGLMModel`]):
|
159
|
+
Frozen text-encoder. Kolors uses [ChatGLM3-6B](https://huggingface.co/THUDM/chatglm3-6b).
|
160
|
+
tokenizer (`ChatGLMTokenizer`):
|
161
|
+
Tokenizer of class
|
162
|
+
[ChatGLMTokenizer](https://huggingface.co/THUDM/chatglm3-6b/blob/main/tokenization_chatglm.py).
|
163
|
+
unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
|
164
|
+
scheduler ([`SchedulerMixin`]):
|
165
|
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
166
|
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
167
|
+
force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"False"`):
|
168
|
+
Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
|
169
|
+
`Kwai-Kolors/Kolors-diffusers`.
|
170
|
+
"""
|
171
|
+
|
172
|
+
model_cpu_offload_seq = "text_encoder->image_encoder-unet->vae"
|
173
|
+
_optional_components = [
|
174
|
+
"image_encoder",
|
175
|
+
"feature_extractor",
|
176
|
+
]
|
177
|
+
_callback_tensor_inputs = [
|
178
|
+
"latents",
|
179
|
+
"prompt_embeds",
|
180
|
+
"negative_prompt_embeds",
|
181
|
+
"add_text_embeds",
|
182
|
+
"add_time_ids",
|
183
|
+
"negative_pooled_prompt_embeds",
|
184
|
+
"negative_add_time_ids",
|
185
|
+
]
|
186
|
+
|
187
|
+
def __init__(
|
188
|
+
self,
|
189
|
+
vae: AutoencoderKL,
|
190
|
+
text_encoder: ChatGLMModel,
|
191
|
+
tokenizer: ChatGLMTokenizer,
|
192
|
+
unet: UNet2DConditionModel,
|
193
|
+
scheduler: KarrasDiffusionSchedulers,
|
194
|
+
image_encoder: CLIPVisionModelWithProjection = None,
|
195
|
+
feature_extractor: CLIPImageProcessor = None,
|
196
|
+
force_zeros_for_empty_prompt: bool = False,
|
197
|
+
):
|
198
|
+
super().__init__()
|
199
|
+
|
200
|
+
self.register_modules(
|
201
|
+
vae=vae,
|
202
|
+
text_encoder=text_encoder,
|
203
|
+
tokenizer=tokenizer,
|
204
|
+
unet=unet,
|
205
|
+
scheduler=scheduler,
|
206
|
+
image_encoder=image_encoder,
|
207
|
+
feature_extractor=feature_extractor,
|
208
|
+
)
|
209
|
+
self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
|
210
|
+
self.vae_scale_factor = (
|
211
|
+
2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
|
212
|
+
)
|
213
|
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
214
|
+
|
215
|
+
self.default_sample_size = self.unet.config.sample_size
|
216
|
+
|
217
|
+
# Copied from diffusers.pipelines.kolors.pipeline_kolors.KolorsPipeline.encode_prompt
|
218
|
+
def encode_prompt(
|
219
|
+
self,
|
220
|
+
prompt,
|
221
|
+
device: Optional[torch.device] = None,
|
222
|
+
num_images_per_prompt: int = 1,
|
223
|
+
do_classifier_free_guidance: bool = True,
|
224
|
+
negative_prompt=None,
|
225
|
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
226
|
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
227
|
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
228
|
+
negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
229
|
+
max_sequence_length: int = 256,
|
230
|
+
):
|
231
|
+
r"""
|
232
|
+
Encodes the prompt into text encoder hidden states.
|
233
|
+
|
234
|
+
Args:
|
235
|
+
prompt (`str` or `List[str]`, *optional*):
|
236
|
+
prompt to be encoded
|
237
|
+
device: (`torch.device`):
|
238
|
+
torch device
|
239
|
+
num_images_per_prompt (`int`):
|
240
|
+
number of images that should be generated per prompt
|
241
|
+
do_classifier_free_guidance (`bool`):
|
242
|
+
whether to use classifier free guidance or not
|
243
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
244
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
245
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
246
|
+
less than `1`).
|
247
|
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
248
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
249
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
250
|
+
pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
251
|
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
252
|
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
253
|
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
254
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
255
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
256
|
+
argument.
|
257
|
+
negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
258
|
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
259
|
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
260
|
+
input argument.
|
261
|
+
max_sequence_length (`int` defaults to 256): Maximum sequence length to use with the `prompt`.
|
262
|
+
"""
|
263
|
+
# from IPython import embed; embed(); exit()
|
264
|
+
device = device or self._execution_device
|
265
|
+
|
266
|
+
if prompt is not None and isinstance(prompt, str):
|
267
|
+
batch_size = 1
|
268
|
+
elif prompt is not None and isinstance(prompt, list):
|
269
|
+
batch_size = len(prompt)
|
270
|
+
else:
|
271
|
+
batch_size = prompt_embeds.shape[0]
|
272
|
+
|
273
|
+
# Define tokenizers and text encoders
|
274
|
+
tokenizers = [self.tokenizer]
|
275
|
+
text_encoders = [self.text_encoder]
|
276
|
+
|
277
|
+
if prompt_embeds is None:
|
278
|
+
prompt_embeds_list = []
|
279
|
+
for tokenizer, text_encoder in zip(tokenizers, text_encoders):
|
280
|
+
text_inputs = tokenizer(
|
281
|
+
prompt,
|
282
|
+
padding="max_length",
|
283
|
+
max_length=max_sequence_length,
|
284
|
+
truncation=True,
|
285
|
+
return_tensors="pt",
|
286
|
+
).to(device)
|
287
|
+
output = text_encoder(
|
288
|
+
input_ids=text_inputs["input_ids"],
|
289
|
+
attention_mask=text_inputs["attention_mask"],
|
290
|
+
position_ids=text_inputs["position_ids"],
|
291
|
+
output_hidden_states=True,
|
292
|
+
)
|
293
|
+
|
294
|
+
# [max_sequence_length, batch, hidden_size] -> [batch, max_sequence_length, hidden_size]
|
295
|
+
# clone to have a contiguous tensor
|
296
|
+
prompt_embeds = output.hidden_states[-2].permute(1, 0, 2).clone()
|
297
|
+
# [max_sequence_length, batch, hidden_size] -> [batch, hidden_size]
|
298
|
+
pooled_prompt_embeds = output.hidden_states[-1][-1, :, :].clone()
|
299
|
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
300
|
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
301
|
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
302
|
+
|
303
|
+
prompt_embeds_list.append(prompt_embeds)
|
304
|
+
|
305
|
+
prompt_embeds = prompt_embeds_list[0]
|
306
|
+
|
307
|
+
# get unconditional embeddings for classifier free guidance
|
308
|
+
zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
|
309
|
+
|
310
|
+
if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
|
311
|
+
negative_prompt_embeds = torch.zeros_like(prompt_embeds)
|
312
|
+
elif do_classifier_free_guidance and negative_prompt_embeds is None:
|
313
|
+
uncond_tokens: List[str]
|
314
|
+
if negative_prompt is None:
|
315
|
+
uncond_tokens = [""] * batch_size
|
316
|
+
elif prompt is not None and type(prompt) is not type(negative_prompt):
|
317
|
+
raise TypeError(
|
318
|
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
319
|
+
f" {type(prompt)}."
|
320
|
+
)
|
321
|
+
elif isinstance(negative_prompt, str):
|
322
|
+
uncond_tokens = [negative_prompt]
|
323
|
+
elif batch_size != len(negative_prompt):
|
324
|
+
raise ValueError(
|
325
|
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
326
|
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
327
|
+
" the batch size of `prompt`."
|
328
|
+
)
|
329
|
+
else:
|
330
|
+
uncond_tokens = negative_prompt
|
331
|
+
|
332
|
+
negative_prompt_embeds_list = []
|
333
|
+
|
334
|
+
for tokenizer, text_encoder in zip(tokenizers, text_encoders):
|
335
|
+
uncond_input = tokenizer(
|
336
|
+
uncond_tokens,
|
337
|
+
padding="max_length",
|
338
|
+
max_length=max_sequence_length,
|
339
|
+
truncation=True,
|
340
|
+
return_tensors="pt",
|
341
|
+
).to(device)
|
342
|
+
output = text_encoder(
|
343
|
+
input_ids=uncond_input["input_ids"],
|
344
|
+
attention_mask=uncond_input["attention_mask"],
|
345
|
+
position_ids=uncond_input["position_ids"],
|
346
|
+
output_hidden_states=True,
|
347
|
+
)
|
348
|
+
|
349
|
+
# [max_sequence_length, batch, hidden_size] -> [batch, max_sequence_length, hidden_size]
|
350
|
+
# clone to have a contiguous tensor
|
351
|
+
negative_prompt_embeds = output.hidden_states[-2].permute(1, 0, 2).clone()
|
352
|
+
# [max_sequence_length, batch, hidden_size] -> [batch, hidden_size]
|
353
|
+
negative_pooled_prompt_embeds = output.hidden_states[-1][-1, :, :].clone()
|
354
|
+
|
355
|
+
if do_classifier_free_guidance:
|
356
|
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
357
|
+
seq_len = negative_prompt_embeds.shape[1]
|
358
|
+
|
359
|
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=text_encoder.dtype, device=device)
|
360
|
+
|
361
|
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
362
|
+
negative_prompt_embeds = negative_prompt_embeds.view(
|
363
|
+
batch_size * num_images_per_prompt, seq_len, -1
|
364
|
+
)
|
365
|
+
|
366
|
+
negative_prompt_embeds_list.append(negative_prompt_embeds)
|
367
|
+
|
368
|
+
negative_prompt_embeds = negative_prompt_embeds_list[0]
|
369
|
+
|
370
|
+
bs_embed = pooled_prompt_embeds.shape[0]
|
371
|
+
pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
372
|
+
bs_embed * num_images_per_prompt, -1
|
373
|
+
)
|
374
|
+
|
375
|
+
if do_classifier_free_guidance:
|
376
|
+
negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
377
|
+
bs_embed * num_images_per_prompt, -1
|
378
|
+
)
|
379
|
+
|
380
|
+
return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
|
381
|
+
|
382
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
|
383
|
+
def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
|
384
|
+
dtype = next(self.image_encoder.parameters()).dtype
|
385
|
+
|
386
|
+
if not isinstance(image, torch.Tensor):
|
387
|
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
388
|
+
|
389
|
+
image = image.to(device=device, dtype=dtype)
|
390
|
+
if output_hidden_states:
|
391
|
+
image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
|
392
|
+
image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
|
393
|
+
uncond_image_enc_hidden_states = self.image_encoder(
|
394
|
+
torch.zeros_like(image), output_hidden_states=True
|
395
|
+
).hidden_states[-2]
|
396
|
+
uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
|
397
|
+
num_images_per_prompt, dim=0
|
398
|
+
)
|
399
|
+
return image_enc_hidden_states, uncond_image_enc_hidden_states
|
400
|
+
else:
|
401
|
+
image_embeds = self.image_encoder(image).image_embeds
|
402
|
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
403
|
+
uncond_image_embeds = torch.zeros_like(image_embeds)
|
404
|
+
|
405
|
+
return image_embeds, uncond_image_embeds
|
406
|
+
|
407
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
|
408
|
+
def prepare_ip_adapter_image_embeds(
|
409
|
+
self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
|
410
|
+
):
|
411
|
+
image_embeds = []
|
412
|
+
if do_classifier_free_guidance:
|
413
|
+
negative_image_embeds = []
|
414
|
+
if ip_adapter_image_embeds is None:
|
415
|
+
if not isinstance(ip_adapter_image, list):
|
416
|
+
ip_adapter_image = [ip_adapter_image]
|
417
|
+
|
418
|
+
if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
|
419
|
+
raise ValueError(
|
420
|
+
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."
|
421
|
+
)
|
422
|
+
|
423
|
+
for single_ip_adapter_image, image_proj_layer in zip(
|
424
|
+
ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
|
425
|
+
):
|
426
|
+
output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
|
427
|
+
single_image_embeds, single_negative_image_embeds = self.encode_image(
|
428
|
+
single_ip_adapter_image, device, 1, output_hidden_state
|
429
|
+
)
|
430
|
+
|
431
|
+
image_embeds.append(single_image_embeds[None, :])
|
432
|
+
if do_classifier_free_guidance:
|
433
|
+
negative_image_embeds.append(single_negative_image_embeds[None, :])
|
434
|
+
else:
|
435
|
+
for single_image_embeds in ip_adapter_image_embeds:
|
436
|
+
if do_classifier_free_guidance:
|
437
|
+
single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
|
438
|
+
negative_image_embeds.append(single_negative_image_embeds)
|
439
|
+
image_embeds.append(single_image_embeds)
|
440
|
+
|
441
|
+
ip_adapter_image_embeds = []
|
442
|
+
for i, single_image_embeds in enumerate(image_embeds):
|
443
|
+
single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
|
444
|
+
if do_classifier_free_guidance:
|
445
|
+
single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
|
446
|
+
single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
|
447
|
+
|
448
|
+
single_image_embeds = single_image_embeds.to(device=device)
|
449
|
+
ip_adapter_image_embeds.append(single_image_embeds)
|
450
|
+
|
451
|
+
return ip_adapter_image_embeds
|
452
|
+
|
453
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
454
|
+
def prepare_extra_step_kwargs(self, generator, eta):
|
455
|
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
456
|
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
457
|
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
458
|
+
# and should be between [0, 1]
|
459
|
+
|
460
|
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
461
|
+
extra_step_kwargs = {}
|
462
|
+
if accepts_eta:
|
463
|
+
extra_step_kwargs["eta"] = eta
|
464
|
+
|
465
|
+
# check if the scheduler accepts generator
|
466
|
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
467
|
+
if accepts_generator:
|
468
|
+
extra_step_kwargs["generator"] = generator
|
469
|
+
return extra_step_kwargs
|
470
|
+
|
471
|
+
def check_inputs(
|
472
|
+
self,
|
473
|
+
prompt,
|
474
|
+
strength,
|
475
|
+
num_inference_steps,
|
476
|
+
height,
|
477
|
+
width,
|
478
|
+
negative_prompt=None,
|
479
|
+
prompt_embeds=None,
|
480
|
+
pooled_prompt_embeds=None,
|
481
|
+
negative_prompt_embeds=None,
|
482
|
+
negative_pooled_prompt_embeds=None,
|
483
|
+
ip_adapter_image=None,
|
484
|
+
ip_adapter_image_embeds=None,
|
485
|
+
callback_on_step_end_tensor_inputs=None,
|
486
|
+
max_sequence_length=None,
|
487
|
+
):
|
488
|
+
if strength < 0 or strength > 1:
|
489
|
+
raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
|
490
|
+
|
491
|
+
if not isinstance(num_inference_steps, int) or num_inference_steps <= 0:
|
492
|
+
raise ValueError(
|
493
|
+
f"`num_inference_steps` has to be a positive integer but is {num_inference_steps} of type"
|
494
|
+
f" {type(num_inference_steps)}."
|
495
|
+
)
|
496
|
+
|
497
|
+
if height % 8 != 0 or width % 8 != 0:
|
498
|
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
499
|
+
|
500
|
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
501
|
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
502
|
+
):
|
503
|
+
raise ValueError(
|
504
|
+
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]}"
|
505
|
+
)
|
506
|
+
|
507
|
+
if prompt is not None and prompt_embeds is not None:
|
508
|
+
raise ValueError(
|
509
|
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
510
|
+
" only forward one of the two."
|
511
|
+
)
|
512
|
+
elif prompt is None and prompt_embeds is None:
|
513
|
+
raise ValueError(
|
514
|
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
515
|
+
)
|
516
|
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
517
|
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
518
|
+
|
519
|
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
520
|
+
raise ValueError(
|
521
|
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
522
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
523
|
+
)
|
524
|
+
|
525
|
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
526
|
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
527
|
+
raise ValueError(
|
528
|
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
529
|
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
530
|
+
f" {negative_prompt_embeds.shape}."
|
531
|
+
)
|
532
|
+
|
533
|
+
if prompt_embeds is not None and pooled_prompt_embeds is None:
|
534
|
+
raise ValueError(
|
535
|
+
"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`."
|
536
|
+
)
|
537
|
+
|
538
|
+
if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
|
539
|
+
raise ValueError(
|
540
|
+
"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`."
|
541
|
+
)
|
542
|
+
|
543
|
+
if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
|
544
|
+
raise ValueError(
|
545
|
+
"Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
|
546
|
+
)
|
547
|
+
|
548
|
+
if ip_adapter_image_embeds is not None:
|
549
|
+
if not isinstance(ip_adapter_image_embeds, list):
|
550
|
+
raise ValueError(
|
551
|
+
f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
|
552
|
+
)
|
553
|
+
elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
|
554
|
+
raise ValueError(
|
555
|
+
f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
|
556
|
+
)
|
557
|
+
|
558
|
+
if max_sequence_length is not None and max_sequence_length > 256:
|
559
|
+
raise ValueError(f"`max_sequence_length` cannot be greater than 256 but is {max_sequence_length}")
|
560
|
+
|
561
|
+
# Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline.get_timesteps
|
562
|
+
def get_timesteps(self, num_inference_steps, strength, device, denoising_start=None):
|
563
|
+
# get the original timestep using init_timestep
|
564
|
+
if denoising_start is None:
|
565
|
+
init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
|
566
|
+
t_start = max(num_inference_steps - init_timestep, 0)
|
567
|
+
|
568
|
+
timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
|
569
|
+
if hasattr(self.scheduler, "set_begin_index"):
|
570
|
+
self.scheduler.set_begin_index(t_start * self.scheduler.order)
|
571
|
+
|
572
|
+
return timesteps, num_inference_steps - t_start
|
573
|
+
|
574
|
+
else:
|
575
|
+
# Strength is irrelevant if we directly request a timestep to start at;
|
576
|
+
# that is, strength is determined by the denoising_start instead.
|
577
|
+
discrete_timestep_cutoff = int(
|
578
|
+
round(
|
579
|
+
self.scheduler.config.num_train_timesteps
|
580
|
+
- (denoising_start * self.scheduler.config.num_train_timesteps)
|
581
|
+
)
|
582
|
+
)
|
583
|
+
|
584
|
+
num_inference_steps = (self.scheduler.timesteps < discrete_timestep_cutoff).sum().item()
|
585
|
+
if self.scheduler.order == 2 and num_inference_steps % 2 == 0:
|
586
|
+
# if the scheduler is a 2nd order scheduler we might have to do +1
|
587
|
+
# because `num_inference_steps` might be even given that every timestep
|
588
|
+
# (except the highest one) is duplicated. If `num_inference_steps` is even it would
|
589
|
+
# mean that we cut the timesteps in the middle of the denoising step
|
590
|
+
# (between 1st and 2nd derivative) which leads to incorrect results. By adding 1
|
591
|
+
# we ensure that the denoising process always ends after the 2nd derivate step of the scheduler
|
592
|
+
num_inference_steps = num_inference_steps + 1
|
593
|
+
|
594
|
+
# because t_n+1 >= t_n, we slice the timesteps starting from the end
|
595
|
+
t_start = len(self.scheduler.timesteps) - num_inference_steps
|
596
|
+
timesteps = self.scheduler.timesteps[t_start:]
|
597
|
+
if hasattr(self.scheduler, "set_begin_index"):
|
598
|
+
self.scheduler.set_begin_index(t_start)
|
599
|
+
return timesteps, num_inference_steps
|
600
|
+
|
601
|
+
# Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline.prepare_latents
|
602
|
+
def prepare_latents(
|
603
|
+
self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None, add_noise=True
|
604
|
+
):
|
605
|
+
if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
|
606
|
+
raise ValueError(
|
607
|
+
f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
|
608
|
+
)
|
609
|
+
|
610
|
+
latents_mean = latents_std = None
|
611
|
+
if hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None:
|
612
|
+
latents_mean = torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1)
|
613
|
+
if hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None:
|
614
|
+
latents_std = torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1)
|
615
|
+
|
616
|
+
# Offload text encoder if `enable_model_cpu_offload` was enabled
|
617
|
+
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
618
|
+
self.text_encoder_2.to("cpu")
|
619
|
+
torch.cuda.empty_cache()
|
620
|
+
|
621
|
+
image = image.to(device=device, dtype=dtype)
|
622
|
+
|
623
|
+
batch_size = batch_size * num_images_per_prompt
|
624
|
+
|
625
|
+
if image.shape[1] == 4:
|
626
|
+
init_latents = image
|
627
|
+
|
628
|
+
else:
|
629
|
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
630
|
+
if self.vae.config.force_upcast:
|
631
|
+
image = image.float()
|
632
|
+
self.vae.to(dtype=torch.float32)
|
633
|
+
|
634
|
+
if isinstance(generator, list) and len(generator) != batch_size:
|
635
|
+
raise ValueError(
|
636
|
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
637
|
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
638
|
+
)
|
639
|
+
|
640
|
+
elif isinstance(generator, list):
|
641
|
+
if image.shape[0] < batch_size and batch_size % image.shape[0] == 0:
|
642
|
+
image = torch.cat([image] * (batch_size // image.shape[0]), dim=0)
|
643
|
+
elif image.shape[0] < batch_size and batch_size % image.shape[0] != 0:
|
644
|
+
raise ValueError(
|
645
|
+
f"Cannot duplicate `image` of batch size {image.shape[0]} to effective batch_size {batch_size} "
|
646
|
+
)
|
647
|
+
|
648
|
+
init_latents = [
|
649
|
+
retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
|
650
|
+
for i in range(batch_size)
|
651
|
+
]
|
652
|
+
init_latents = torch.cat(init_latents, dim=0)
|
653
|
+
else:
|
654
|
+
init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
|
655
|
+
|
656
|
+
if self.vae.config.force_upcast:
|
657
|
+
self.vae.to(dtype)
|
658
|
+
|
659
|
+
init_latents = init_latents.to(dtype)
|
660
|
+
if latents_mean is not None and latents_std is not None:
|
661
|
+
latents_mean = latents_mean.to(device=device, dtype=dtype)
|
662
|
+
latents_std = latents_std.to(device=device, dtype=dtype)
|
663
|
+
init_latents = (init_latents - latents_mean) * self.vae.config.scaling_factor / latents_std
|
664
|
+
else:
|
665
|
+
init_latents = self.vae.config.scaling_factor * init_latents
|
666
|
+
|
667
|
+
if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
|
668
|
+
# expand init_latents for batch_size
|
669
|
+
additional_image_per_prompt = batch_size // init_latents.shape[0]
|
670
|
+
init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
|
671
|
+
elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
|
672
|
+
raise ValueError(
|
673
|
+
f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
|
674
|
+
)
|
675
|
+
else:
|
676
|
+
init_latents = torch.cat([init_latents], dim=0)
|
677
|
+
|
678
|
+
if add_noise:
|
679
|
+
shape = init_latents.shape
|
680
|
+
noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
681
|
+
# get latents
|
682
|
+
init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
|
683
|
+
|
684
|
+
latents = init_latents
|
685
|
+
|
686
|
+
return latents
|
687
|
+
|
688
|
+
# Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline._get_add_time_ids
|
689
|
+
def _get_add_time_ids(
|
690
|
+
self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
|
691
|
+
):
|
692
|
+
add_time_ids = list(original_size + crops_coords_top_left + target_size)
|
693
|
+
|
694
|
+
passed_add_embed_dim = (
|
695
|
+
self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
|
696
|
+
)
|
697
|
+
expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
|
698
|
+
|
699
|
+
if expected_add_embed_dim != passed_add_embed_dim:
|
700
|
+
raise ValueError(
|
701
|
+
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
|
702
|
+
)
|
703
|
+
|
704
|
+
add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
|
705
|
+
return add_time_ids
|
706
|
+
|
707
|
+
# Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.upcast_vae
|
708
|
+
def upcast_vae(self):
|
709
|
+
dtype = self.vae.dtype
|
710
|
+
self.vae.to(dtype=torch.float32)
|
711
|
+
use_torch_2_0_or_xformers = isinstance(
|
712
|
+
self.vae.decoder.mid_block.attentions[0].processor,
|
713
|
+
(
|
714
|
+
AttnProcessor2_0,
|
715
|
+
XFormersAttnProcessor,
|
716
|
+
FusedAttnProcessor2_0,
|
717
|
+
),
|
718
|
+
)
|
719
|
+
# if xformers or torch_2_0 is used attention block does not need
|
720
|
+
# to be in float32 which can save lots of memory
|
721
|
+
if use_torch_2_0_or_xformers:
|
722
|
+
self.vae.post_quant_conv.to(dtype)
|
723
|
+
self.vae.decoder.conv_in.to(dtype)
|
724
|
+
self.vae.decoder.mid_block.to(dtype)
|
725
|
+
|
726
|
+
# Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
|
727
|
+
def get_guidance_scale_embedding(
|
728
|
+
self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
|
729
|
+
) -> torch.Tensor:
|
730
|
+
"""
|
731
|
+
See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
|
732
|
+
|
733
|
+
Args:
|
734
|
+
w (`torch.Tensor`):
|
735
|
+
Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
|
736
|
+
embedding_dim (`int`, *optional*, defaults to 512):
|
737
|
+
Dimension of the embeddings to generate.
|
738
|
+
dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
|
739
|
+
Data type of the generated embeddings.
|
740
|
+
|
741
|
+
Returns:
|
742
|
+
`torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
|
743
|
+
"""
|
744
|
+
assert len(w.shape) == 1
|
745
|
+
w = w * 1000.0
|
746
|
+
|
747
|
+
half_dim = embedding_dim // 2
|
748
|
+
emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
|
749
|
+
emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
|
750
|
+
emb = w.to(dtype)[:, None] * emb[None, :]
|
751
|
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
752
|
+
if embedding_dim % 2 == 1: # zero pad
|
753
|
+
emb = torch.nn.functional.pad(emb, (0, 1))
|
754
|
+
assert emb.shape == (w.shape[0], embedding_dim)
|
755
|
+
return emb
|
756
|
+
|
757
|
+
@property
|
758
|
+
def guidance_scale(self):
|
759
|
+
return self._guidance_scale
|
760
|
+
|
761
|
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
762
|
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
763
|
+
# corresponds to doing no classifier free guidance.
|
764
|
+
@property
|
765
|
+
def do_classifier_free_guidance(self):
|
766
|
+
return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
|
767
|
+
|
768
|
+
@property
|
769
|
+
def cross_attention_kwargs(self):
|
770
|
+
return self._cross_attention_kwargs
|
771
|
+
|
772
|
+
@property
|
773
|
+
def denoising_start(self):
|
774
|
+
return self._denoising_start
|
775
|
+
|
776
|
+
@property
|
777
|
+
def denoising_end(self):
|
778
|
+
return self._denoising_end
|
779
|
+
|
780
|
+
@property
|
781
|
+
def num_timesteps(self):
|
782
|
+
return self._num_timesteps
|
783
|
+
|
784
|
+
@property
|
785
|
+
def interrupt(self):
|
786
|
+
return self._interrupt
|
787
|
+
|
788
|
+
@torch.no_grad()
|
789
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
790
|
+
def __call__(
|
791
|
+
self,
|
792
|
+
prompt: Union[str, List[str]] = None,
|
793
|
+
image: PipelineImageInput = None,
|
794
|
+
strength: float = 0.3,
|
795
|
+
height: Optional[int] = None,
|
796
|
+
width: Optional[int] = None,
|
797
|
+
num_inference_steps: int = 50,
|
798
|
+
timesteps: List[int] = None,
|
799
|
+
sigmas: List[float] = None,
|
800
|
+
denoising_start: Optional[float] = None,
|
801
|
+
denoising_end: Optional[float] = None,
|
802
|
+
guidance_scale: float = 5.0,
|
803
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
804
|
+
num_images_per_prompt: Optional[int] = 1,
|
805
|
+
eta: float = 0.0,
|
806
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
807
|
+
latents: Optional[torch.Tensor] = None,
|
808
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
809
|
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
810
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
811
|
+
negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
812
|
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
813
|
+
ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
|
814
|
+
output_type: Optional[str] = "pil",
|
815
|
+
return_dict: bool = True,
|
816
|
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
817
|
+
original_size: Optional[Tuple[int, int]] = None,
|
818
|
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
819
|
+
target_size: Optional[Tuple[int, int]] = None,
|
820
|
+
negative_original_size: Optional[Tuple[int, int]] = None,
|
821
|
+
negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
|
822
|
+
negative_target_size: Optional[Tuple[int, int]] = None,
|
823
|
+
callback_on_step_end: Optional[
|
824
|
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
825
|
+
] = None,
|
826
|
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
827
|
+
max_sequence_length: int = 256,
|
828
|
+
):
|
829
|
+
r"""
|
830
|
+
Function invoked when calling the pipeline for generation.
|
831
|
+
|
832
|
+
Args:
|
833
|
+
prompt (`str` or `List[str]`, *optional*):
|
834
|
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
835
|
+
instead.
|
836
|
+
image (`torch.Tensor` or `PIL.Image.Image` or `np.ndarray` or `List[torch.Tensor]` or `List[PIL.Image.Image]` or `List[np.ndarray]`):
|
837
|
+
The image(s) to modify with the pipeline.
|
838
|
+
strength (`float`, *optional*, defaults to 0.3):
|
839
|
+
Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
|
840
|
+
will be used as a starting point, adding more noise to it the larger the `strength`. The number of
|
841
|
+
denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
|
842
|
+
be maximum and the denoising process will run for the full number of iterations specified in
|
843
|
+
`num_inference_steps`. A value of 1, therefore, essentially ignores `image`. Note that in the case of
|
844
|
+
`denoising_start` being declared as an integer, the value of `strength` will be ignored.
|
845
|
+
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
846
|
+
The height in pixels of the generated image. This is set to 1024 by default for the best results.
|
847
|
+
Anything below 512 pixels won't work well for
|
848
|
+
[Kwai-Kolors/Kolors-diffusers](https://huggingface.co/Kwai-Kolors/Kolors-diffusers) and checkpoints
|
849
|
+
that are not specifically fine-tuned on low resolutions.
|
850
|
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
851
|
+
The width in pixels of the generated image. This is set to 1024 by default for the best results.
|
852
|
+
Anything below 512 pixels won't work well for
|
853
|
+
[Kwai-Kolors/Kolors-diffusers](https://huggingface.co/Kwai-Kolors/Kolors-diffusers) and checkpoints
|
854
|
+
that are not specifically fine-tuned on low resolutions.
|
855
|
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
856
|
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
857
|
+
expense of slower inference.
|
858
|
+
timesteps (`List[int]`, *optional*):
|
859
|
+
Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
|
860
|
+
in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
|
861
|
+
passed will be used. Must be in descending order.
|
862
|
+
sigmas (`List[float]`, *optional*):
|
863
|
+
Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
|
864
|
+
their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
|
865
|
+
will be used.
|
866
|
+
denoising_start (`float`, *optional*):
|
867
|
+
When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be
|
868
|
+
bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and
|
869
|
+
it is assumed that the passed `image` is a partly denoised image. Note that when this is specified,
|
870
|
+
strength will be ignored. The `denoising_start` parameter is particularly beneficial when this pipeline
|
871
|
+
is integrated into a "Mixture of Denoisers" multi-pipeline setup, as detailed in [**Refine Image
|
872
|
+
Quality**](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#refine-image-quality).
|
873
|
+
denoising_end (`float`, *optional*):
|
874
|
+
When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
|
875
|
+
completed before it is intentionally prematurely terminated. As a result, the returned sample will
|
876
|
+
still retain a substantial amount of noise as determined by the discrete timesteps selected by the
|
877
|
+
scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
|
878
|
+
"Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
|
879
|
+
Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
|
880
|
+
guidance_scale (`float`, *optional*, defaults to 5.0):
|
881
|
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
882
|
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
883
|
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
884
|
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
885
|
+
usually at the expense of lower image quality.
|
886
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
887
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
888
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
889
|
+
less than `1`).
|
890
|
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
891
|
+
The number of images to generate per prompt.
|
892
|
+
eta (`float`, *optional*, defaults to 0.0):
|
893
|
+
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
894
|
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
895
|
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
896
|
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
897
|
+
to make generation deterministic.
|
898
|
+
latents (`torch.Tensor`, *optional*):
|
899
|
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
900
|
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
901
|
+
tensor will ge generated by sampling using the supplied random `generator`.
|
902
|
+
prompt_embeds (`torch.Tensor`, *optional*):
|
903
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
904
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
905
|
+
pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
906
|
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
907
|
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
908
|
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
909
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
910
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
911
|
+
argument.
|
912
|
+
negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
913
|
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
914
|
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
915
|
+
input argument.
|
916
|
+
ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
|
917
|
+
ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
|
918
|
+
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
|
919
|
+
IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
|
920
|
+
contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
|
921
|
+
provided, embeddings are computed from the `ip_adapter_image` input argument.
|
922
|
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
923
|
+
The output format of the generate image. Choose between
|
924
|
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
925
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
926
|
+
Whether or not to return a [`~pipelines.kolors.KolorsPipelineOutput`] instead of a plain tuple.
|
927
|
+
cross_attention_kwargs (`dict`, *optional*):
|
928
|
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
929
|
+
`self.processor` in
|
930
|
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
931
|
+
original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
932
|
+
If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
|
933
|
+
`original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
|
934
|
+
explained in section 2.2 of
|
935
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
936
|
+
crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
937
|
+
`crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
|
938
|
+
`crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
|
939
|
+
`crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
|
940
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
941
|
+
target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
942
|
+
For most cases, `target_size` should be set to the desired height and width of the generated image. If
|
943
|
+
not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
|
944
|
+
section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
945
|
+
negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
946
|
+
To negatively condition the generation process based on a specific image resolution. Part of SDXL's
|
947
|
+
micro-conditioning as explained in section 2.2 of
|
948
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
949
|
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
950
|
+
negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
951
|
+
To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
|
952
|
+
micro-conditioning as explained in section 2.2 of
|
953
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
954
|
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
955
|
+
negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
956
|
+
To negatively condition the generation process based on a target image resolution. It should be as same
|
957
|
+
as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
|
958
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
959
|
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
960
|
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
961
|
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
962
|
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
963
|
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
964
|
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
965
|
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
966
|
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
967
|
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
968
|
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
969
|
+
max_sequence_length (`int` defaults to 256): Maximum sequence length to use with the `prompt`.
|
970
|
+
|
971
|
+
Examples:
|
972
|
+
|
973
|
+
Returns:
|
974
|
+
[`~pipelines.kolors.KolorsPipelineOutput`] or `tuple`: [`~pipelines.kolors.KolorsPipelineOutput`] if
|
975
|
+
`return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the
|
976
|
+
generated images.
|
977
|
+
"""
|
978
|
+
|
979
|
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
980
|
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
981
|
+
|
982
|
+
# 0. Default height and width to unet
|
983
|
+
height = height or self.default_sample_size * self.vae_scale_factor
|
984
|
+
width = width or self.default_sample_size * self.vae_scale_factor
|
985
|
+
|
986
|
+
original_size = original_size or (height, width)
|
987
|
+
target_size = target_size or (height, width)
|
988
|
+
|
989
|
+
# 1. Check inputs. Raise error if not correct
|
990
|
+
self.check_inputs(
|
991
|
+
prompt,
|
992
|
+
strength,
|
993
|
+
num_inference_steps,
|
994
|
+
height,
|
995
|
+
width,
|
996
|
+
negative_prompt,
|
997
|
+
prompt_embeds,
|
998
|
+
pooled_prompt_embeds,
|
999
|
+
negative_prompt_embeds,
|
1000
|
+
negative_pooled_prompt_embeds,
|
1001
|
+
ip_adapter_image,
|
1002
|
+
ip_adapter_image_embeds,
|
1003
|
+
callback_on_step_end_tensor_inputs,
|
1004
|
+
max_sequence_length=max_sequence_length,
|
1005
|
+
)
|
1006
|
+
|
1007
|
+
self._guidance_scale = guidance_scale
|
1008
|
+
self._cross_attention_kwargs = cross_attention_kwargs
|
1009
|
+
self._denoising_end = denoising_end
|
1010
|
+
self._denoising_start = denoising_start
|
1011
|
+
self._interrupt = False
|
1012
|
+
|
1013
|
+
# 2. Define call parameters
|
1014
|
+
if prompt is not None and isinstance(prompt, str):
|
1015
|
+
batch_size = 1
|
1016
|
+
elif prompt is not None and isinstance(prompt, list):
|
1017
|
+
batch_size = len(prompt)
|
1018
|
+
else:
|
1019
|
+
batch_size = prompt_embeds.shape[0]
|
1020
|
+
|
1021
|
+
device = self._execution_device
|
1022
|
+
|
1023
|
+
# 3. Encode input prompt
|
1024
|
+
(
|
1025
|
+
prompt_embeds,
|
1026
|
+
negative_prompt_embeds,
|
1027
|
+
pooled_prompt_embeds,
|
1028
|
+
negative_pooled_prompt_embeds,
|
1029
|
+
) = self.encode_prompt(
|
1030
|
+
prompt=prompt,
|
1031
|
+
device=device,
|
1032
|
+
num_images_per_prompt=num_images_per_prompt,
|
1033
|
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
1034
|
+
negative_prompt=negative_prompt,
|
1035
|
+
prompt_embeds=prompt_embeds,
|
1036
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
1037
|
+
)
|
1038
|
+
|
1039
|
+
# 4. Preprocess image
|
1040
|
+
image = self.image_processor.preprocess(image)
|
1041
|
+
|
1042
|
+
# 5. Prepare timesteps
|
1043
|
+
def denoising_value_valid(dnv):
|
1044
|
+
return isinstance(dnv, float) and 0 < dnv < 1
|
1045
|
+
|
1046
|
+
timesteps, num_inference_steps = retrieve_timesteps(
|
1047
|
+
self.scheduler, num_inference_steps, device, timesteps, sigmas
|
1048
|
+
)
|
1049
|
+
|
1050
|
+
timesteps, num_inference_steps = self.get_timesteps(
|
1051
|
+
num_inference_steps,
|
1052
|
+
strength,
|
1053
|
+
device,
|
1054
|
+
denoising_start=self.denoising_start if denoising_value_valid(self.denoising_start) else None,
|
1055
|
+
)
|
1056
|
+
latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
|
1057
|
+
|
1058
|
+
add_noise = True if self.denoising_start is None else False
|
1059
|
+
|
1060
|
+
# 6. Prepare latent variables
|
1061
|
+
if latents is None:
|
1062
|
+
latents = self.prepare_latents(
|
1063
|
+
image,
|
1064
|
+
latent_timestep,
|
1065
|
+
batch_size,
|
1066
|
+
num_images_per_prompt,
|
1067
|
+
prompt_embeds.dtype,
|
1068
|
+
device,
|
1069
|
+
generator,
|
1070
|
+
add_noise,
|
1071
|
+
)
|
1072
|
+
|
1073
|
+
# 7. Prepare extra step kwargs.
|
1074
|
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
1075
|
+
|
1076
|
+
height, width = latents.shape[-2:]
|
1077
|
+
height = height * self.vae_scale_factor
|
1078
|
+
width = width * self.vae_scale_factor
|
1079
|
+
|
1080
|
+
original_size = original_size or (height, width)
|
1081
|
+
target_size = target_size or (height, width)
|
1082
|
+
|
1083
|
+
# 8. Prepare added time ids & embeddings
|
1084
|
+
add_text_embeds = pooled_prompt_embeds
|
1085
|
+
text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
|
1086
|
+
|
1087
|
+
add_time_ids = self._get_add_time_ids(
|
1088
|
+
original_size,
|
1089
|
+
crops_coords_top_left,
|
1090
|
+
target_size,
|
1091
|
+
dtype=prompt_embeds.dtype,
|
1092
|
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
1093
|
+
)
|
1094
|
+
if negative_original_size is not None and negative_target_size is not None:
|
1095
|
+
negative_add_time_ids = self._get_add_time_ids(
|
1096
|
+
negative_original_size,
|
1097
|
+
negative_crops_coords_top_left,
|
1098
|
+
negative_target_size,
|
1099
|
+
dtype=prompt_embeds.dtype,
|
1100
|
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
1101
|
+
)
|
1102
|
+
else:
|
1103
|
+
negative_add_time_ids = add_time_ids
|
1104
|
+
|
1105
|
+
if self.do_classifier_free_guidance:
|
1106
|
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
1107
|
+
add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
|
1108
|
+
add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
|
1109
|
+
|
1110
|
+
prompt_embeds = prompt_embeds.to(device)
|
1111
|
+
add_text_embeds = add_text_embeds.to(device)
|
1112
|
+
add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
|
1113
|
+
|
1114
|
+
if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
|
1115
|
+
image_embeds = self.prepare_ip_adapter_image_embeds(
|
1116
|
+
ip_adapter_image,
|
1117
|
+
ip_adapter_image_embeds,
|
1118
|
+
device,
|
1119
|
+
batch_size * num_images_per_prompt,
|
1120
|
+
self.do_classifier_free_guidance,
|
1121
|
+
)
|
1122
|
+
|
1123
|
+
# 9. Denoising loop
|
1124
|
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
1125
|
+
|
1126
|
+
# 9.1 Apply denoising_end
|
1127
|
+
if (
|
1128
|
+
self.denoising_end is not None
|
1129
|
+
and self.denoising_start is not None
|
1130
|
+
and denoising_value_valid(self.denoising_end)
|
1131
|
+
and denoising_value_valid(self.denoising_start)
|
1132
|
+
and self.denoising_start >= self.denoising_end
|
1133
|
+
):
|
1134
|
+
raise ValueError(
|
1135
|
+
f"`denoising_start`: {self.denoising_start} cannot be larger than or equal to `denoising_end`: "
|
1136
|
+
+ f" {self.denoising_end} when using type float."
|
1137
|
+
)
|
1138
|
+
elif self.denoising_end is not None and denoising_value_valid(self.denoising_end):
|
1139
|
+
discrete_timestep_cutoff = int(
|
1140
|
+
round(
|
1141
|
+
self.scheduler.config.num_train_timesteps
|
1142
|
+
- (self.denoising_end * self.scheduler.config.num_train_timesteps)
|
1143
|
+
)
|
1144
|
+
)
|
1145
|
+
num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
|
1146
|
+
timesteps = timesteps[:num_inference_steps]
|
1147
|
+
|
1148
|
+
# 9.2 Optionally get Guidance Scale Embedding
|
1149
|
+
timestep_cond = None
|
1150
|
+
if self.unet.config.time_cond_proj_dim is not None:
|
1151
|
+
guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
|
1152
|
+
timestep_cond = self.get_guidance_scale_embedding(
|
1153
|
+
guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
|
1154
|
+
).to(device=device, dtype=latents.dtype)
|
1155
|
+
|
1156
|
+
self._num_timesteps = len(timesteps)
|
1157
|
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
1158
|
+
for i, t in enumerate(timesteps):
|
1159
|
+
if self.interrupt:
|
1160
|
+
continue
|
1161
|
+
|
1162
|
+
# expand the latents if we are doing classifier free guidance
|
1163
|
+
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
1164
|
+
|
1165
|
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
1166
|
+
|
1167
|
+
# predict the noise residual
|
1168
|
+
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
1169
|
+
|
1170
|
+
if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
|
1171
|
+
added_cond_kwargs["image_embeds"] = image_embeds
|
1172
|
+
|
1173
|
+
noise_pred = self.unet(
|
1174
|
+
latent_model_input,
|
1175
|
+
t,
|
1176
|
+
encoder_hidden_states=prompt_embeds,
|
1177
|
+
timestep_cond=timestep_cond,
|
1178
|
+
cross_attention_kwargs=self.cross_attention_kwargs,
|
1179
|
+
added_cond_kwargs=added_cond_kwargs,
|
1180
|
+
return_dict=False,
|
1181
|
+
)[0]
|
1182
|
+
|
1183
|
+
# perform guidance
|
1184
|
+
if self.do_classifier_free_guidance:
|
1185
|
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
1186
|
+
noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
|
1187
|
+
|
1188
|
+
# compute the previous noisy sample x_t -> x_t-1
|
1189
|
+
latents_dtype = latents.dtype
|
1190
|
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
1191
|
+
if latents.dtype != latents_dtype:
|
1192
|
+
if torch.backends.mps.is_available():
|
1193
|
+
# some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
|
1194
|
+
latents = latents.to(latents_dtype)
|
1195
|
+
|
1196
|
+
if callback_on_step_end is not None:
|
1197
|
+
callback_kwargs = {}
|
1198
|
+
for k in callback_on_step_end_tensor_inputs:
|
1199
|
+
callback_kwargs[k] = locals()[k]
|
1200
|
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
1201
|
+
|
1202
|
+
latents = callback_outputs.pop("latents", latents)
|
1203
|
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
1204
|
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
1205
|
+
add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
|
1206
|
+
negative_pooled_prompt_embeds = callback_outputs.pop(
|
1207
|
+
"negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
|
1208
|
+
)
|
1209
|
+
add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
|
1210
|
+
negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
|
1211
|
+
|
1212
|
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
1213
|
+
progress_bar.update()
|
1214
|
+
|
1215
|
+
if XLA_AVAILABLE:
|
1216
|
+
xm.mark_step()
|
1217
|
+
|
1218
|
+
if not output_type == "latent":
|
1219
|
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
1220
|
+
needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
|
1221
|
+
|
1222
|
+
if needs_upcasting:
|
1223
|
+
self.upcast_vae()
|
1224
|
+
latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
1225
|
+
elif latents.dtype != self.vae.dtype:
|
1226
|
+
if torch.backends.mps.is_available():
|
1227
|
+
# some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
|
1228
|
+
self.vae = self.vae.to(latents.dtype)
|
1229
|
+
|
1230
|
+
# unscale/denormalize the latents
|
1231
|
+
latents = latents / self.vae.config.scaling_factor
|
1232
|
+
|
1233
|
+
image = self.vae.decode(latents, return_dict=False)[0]
|
1234
|
+
|
1235
|
+
# cast back to fp16 if needed
|
1236
|
+
if needs_upcasting:
|
1237
|
+
self.vae.to(dtype=torch.float16)
|
1238
|
+
else:
|
1239
|
+
image = latents
|
1240
|
+
|
1241
|
+
if not output_type == "latent":
|
1242
|
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
1243
|
+
|
1244
|
+
# Offload all models
|
1245
|
+
self.maybe_free_model_hooks()
|
1246
|
+
|
1247
|
+
if not return_dict:
|
1248
|
+
return (image,)
|
1249
|
+
|
1250
|
+
return KolorsPipelineOutput(images=image)
|