diffusers 0.33.0__py3-none-any.whl → 0.34.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- diffusers/__init__.py +48 -1
- diffusers/commands/__init__.py +1 -1
- diffusers/commands/diffusers_cli.py +1 -1
- diffusers/commands/env.py +1 -1
- diffusers/commands/fp16_safetensors.py +1 -1
- diffusers/dependency_versions_check.py +1 -1
- diffusers/dependency_versions_table.py +1 -1
- diffusers/experimental/rl/value_guided_sampling.py +1 -1
- diffusers/hooks/faster_cache.py +2 -2
- diffusers/hooks/group_offloading.py +128 -29
- diffusers/hooks/hooks.py +2 -2
- diffusers/hooks/layerwise_casting.py +3 -3
- diffusers/hooks/pyramid_attention_broadcast.py +1 -1
- diffusers/image_processor.py +7 -2
- diffusers/loaders/__init__.py +4 -0
- diffusers/loaders/ip_adapter.py +5 -14
- diffusers/loaders/lora_base.py +212 -111
- diffusers/loaders/lora_conversion_utils.py +275 -34
- diffusers/loaders/lora_pipeline.py +1554 -819
- diffusers/loaders/peft.py +52 -109
- diffusers/loaders/single_file.py +2 -2
- diffusers/loaders/single_file_model.py +20 -4
- diffusers/loaders/single_file_utils.py +225 -5
- diffusers/loaders/textual_inversion.py +3 -2
- diffusers/loaders/transformer_flux.py +1 -1
- diffusers/loaders/transformer_sd3.py +2 -2
- diffusers/loaders/unet.py +2 -16
- diffusers/loaders/unet_loader_utils.py +1 -1
- diffusers/loaders/utils.py +1 -1
- diffusers/models/__init__.py +15 -1
- diffusers/models/activations.py +5 -5
- diffusers/models/adapter.py +2 -3
- diffusers/models/attention.py +4 -4
- diffusers/models/attention_flax.py +10 -10
- diffusers/models/attention_processor.py +14 -10
- diffusers/models/auto_model.py +47 -10
- diffusers/models/autoencoders/__init__.py +1 -0
- diffusers/models/autoencoders/autoencoder_asym_kl.py +4 -4
- diffusers/models/autoencoders/autoencoder_dc.py +3 -3
- diffusers/models/autoencoders/autoencoder_kl.py +4 -4
- diffusers/models/autoencoders/autoencoder_kl_allegro.py +4 -4
- diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +6 -6
- diffusers/models/autoencoders/autoencoder_kl_cosmos.py +1108 -0
- diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py +2 -2
- diffusers/models/autoencoders/autoencoder_kl_ltx.py +3 -3
- diffusers/models/autoencoders/autoencoder_kl_magvit.py +4 -4
- diffusers/models/autoencoders/autoencoder_kl_mochi.py +3 -3
- diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +4 -4
- diffusers/models/autoencoders/autoencoder_kl_wan.py +256 -22
- diffusers/models/autoencoders/autoencoder_oobleck.py +1 -1
- diffusers/models/autoencoders/autoencoder_tiny.py +3 -3
- diffusers/models/autoencoders/consistency_decoder_vae.py +1 -1
- diffusers/models/autoencoders/vae.py +13 -2
- diffusers/models/autoencoders/vq_model.py +2 -2
- diffusers/models/cache_utils.py +1 -1
- diffusers/models/controlnet.py +1 -1
- diffusers/models/controlnet_flux.py +1 -1
- diffusers/models/controlnet_sd3.py +1 -1
- diffusers/models/controlnet_sparsectrl.py +1 -1
- diffusers/models/controlnets/__init__.py +1 -0
- diffusers/models/controlnets/controlnet.py +3 -3
- diffusers/models/controlnets/controlnet_flax.py +1 -1
- diffusers/models/controlnets/controlnet_flux.py +16 -15
- diffusers/models/controlnets/controlnet_hunyuan.py +2 -2
- diffusers/models/controlnets/controlnet_sana.py +290 -0
- diffusers/models/controlnets/controlnet_sd3.py +1 -1
- diffusers/models/controlnets/controlnet_sparsectrl.py +2 -2
- diffusers/models/controlnets/controlnet_union.py +1 -1
- diffusers/models/controlnets/controlnet_xs.py +7 -7
- diffusers/models/controlnets/multicontrolnet.py +4 -5
- diffusers/models/controlnets/multicontrolnet_union.py +5 -6
- diffusers/models/downsampling.py +2 -2
- diffusers/models/embeddings.py +10 -12
- diffusers/models/embeddings_flax.py +2 -2
- diffusers/models/lora.py +3 -3
- diffusers/models/modeling_utils.py +44 -14
- diffusers/models/normalization.py +4 -4
- diffusers/models/resnet.py +2 -2
- diffusers/models/resnet_flax.py +1 -1
- diffusers/models/transformers/__init__.py +5 -0
- diffusers/models/transformers/auraflow_transformer_2d.py +70 -24
- diffusers/models/transformers/cogvideox_transformer_3d.py +1 -1
- diffusers/models/transformers/consisid_transformer_3d.py +1 -1
- diffusers/models/transformers/dit_transformer_2d.py +2 -2
- diffusers/models/transformers/dual_transformer_2d.py +1 -1
- diffusers/models/transformers/hunyuan_transformer_2d.py +2 -2
- diffusers/models/transformers/latte_transformer_3d.py +4 -5
- diffusers/models/transformers/lumina_nextdit2d.py +2 -2
- diffusers/models/transformers/pixart_transformer_2d.py +3 -3
- diffusers/models/transformers/prior_transformer.py +1 -1
- diffusers/models/transformers/sana_transformer.py +8 -3
- diffusers/models/transformers/stable_audio_transformer.py +5 -9
- diffusers/models/transformers/t5_film_transformer.py +3 -3
- diffusers/models/transformers/transformer_2d.py +1 -1
- diffusers/models/transformers/transformer_allegro.py +1 -1
- diffusers/models/transformers/transformer_chroma.py +742 -0
- diffusers/models/transformers/transformer_cogview3plus.py +5 -10
- diffusers/models/transformers/transformer_cogview4.py +317 -25
- diffusers/models/transformers/transformer_cosmos.py +579 -0
- diffusers/models/transformers/transformer_flux.py +9 -11
- diffusers/models/transformers/transformer_hidream_image.py +942 -0
- diffusers/models/transformers/transformer_hunyuan_video.py +6 -8
- diffusers/models/transformers/transformer_hunyuan_video_framepack.py +416 -0
- diffusers/models/transformers/transformer_ltx.py +2 -2
- diffusers/models/transformers/transformer_lumina2.py +1 -1
- diffusers/models/transformers/transformer_mochi.py +1 -1
- diffusers/models/transformers/transformer_omnigen.py +2 -2
- diffusers/models/transformers/transformer_sd3.py +7 -7
- diffusers/models/transformers/transformer_temporal.py +1 -1
- diffusers/models/transformers/transformer_wan.py +24 -8
- diffusers/models/transformers/transformer_wan_vace.py +393 -0
- diffusers/models/unets/unet_1d.py +1 -1
- diffusers/models/unets/unet_1d_blocks.py +1 -1
- diffusers/models/unets/unet_2d.py +1 -1
- diffusers/models/unets/unet_2d_blocks.py +1 -1
- diffusers/models/unets/unet_2d_blocks_flax.py +8 -7
- diffusers/models/unets/unet_2d_condition.py +2 -2
- diffusers/models/unets/unet_2d_condition_flax.py +2 -2
- diffusers/models/unets/unet_3d_blocks.py +1 -1
- diffusers/models/unets/unet_3d_condition.py +3 -3
- diffusers/models/unets/unet_i2vgen_xl.py +3 -3
- diffusers/models/unets/unet_kandinsky3.py +1 -1
- diffusers/models/unets/unet_motion_model.py +2 -2
- diffusers/models/unets/unet_stable_cascade.py +1 -1
- diffusers/models/upsampling.py +2 -2
- diffusers/models/vae_flax.py +2 -2
- diffusers/models/vq_model.py +1 -1
- diffusers/pipelines/__init__.py +37 -6
- diffusers/pipelines/allegro/pipeline_allegro.py +11 -11
- diffusers/pipelines/amused/pipeline_amused.py +7 -6
- diffusers/pipelines/amused/pipeline_amused_img2img.py +6 -5
- diffusers/pipelines/amused/pipeline_amused_inpaint.py +6 -5
- diffusers/pipelines/animatediff/pipeline_animatediff.py +6 -6
- diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +6 -6
- diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +16 -15
- diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +6 -6
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +5 -5
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +5 -5
- diffusers/pipelines/audioldm/pipeline_audioldm.py +8 -7
- diffusers/pipelines/audioldm2/modeling_audioldm2.py +1 -1
- diffusers/pipelines/audioldm2/pipeline_audioldm2.py +23 -13
- diffusers/pipelines/aura_flow/pipeline_aura_flow.py +48 -11
- diffusers/pipelines/auto_pipeline.py +6 -7
- diffusers/pipelines/blip_diffusion/modeling_blip2.py +1 -1
- diffusers/pipelines/blip_diffusion/modeling_ctx_clip.py +2 -2
- diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +11 -10
- diffusers/pipelines/chroma/__init__.py +49 -0
- diffusers/pipelines/chroma/pipeline_chroma.py +949 -0
- diffusers/pipelines/chroma/pipeline_chroma_img2img.py +1034 -0
- diffusers/pipelines/chroma/pipeline_output.py +21 -0
- diffusers/pipelines/cogvideo/pipeline_cogvideox.py +8 -8
- diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +8 -8
- diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +8 -8
- diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +8 -8
- diffusers/pipelines/cogview3/pipeline_cogview3plus.py +9 -9
- diffusers/pipelines/cogview4/pipeline_cogview4.py +7 -7
- diffusers/pipelines/cogview4/pipeline_cogview4_control.py +7 -7
- diffusers/pipelines/consisid/consisid_utils.py +2 -2
- diffusers/pipelines/consisid/pipeline_consisid.py +8 -8
- diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -1
- diffusers/pipelines/controlnet/pipeline_controlnet.py +7 -7
- diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +8 -8
- diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +7 -7
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +7 -7
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +14 -14
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +10 -6
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +13 -13
- diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +14 -14
- diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +5 -5
- diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +13 -13
- diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +1 -1
- diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +8 -8
- diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +7 -7
- diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +7 -7
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +12 -10
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +9 -7
- diffusers/pipelines/cosmos/__init__.py +54 -0
- diffusers/pipelines/cosmos/pipeline_cosmos2_text2image.py +673 -0
- diffusers/pipelines/cosmos/pipeline_cosmos2_video2world.py +792 -0
- diffusers/pipelines/cosmos/pipeline_cosmos_text2world.py +664 -0
- diffusers/pipelines/cosmos/pipeline_cosmos_video2world.py +826 -0
- diffusers/pipelines/cosmos/pipeline_output.py +40 -0
- diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +5 -4
- diffusers/pipelines/ddim/pipeline_ddim.py +4 -4
- diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if.py +10 -10
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +10 -10
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +10 -10
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +10 -10
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +10 -10
- diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +10 -10
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +8 -8
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +5 -5
- diffusers/pipelines/deprecated/audio_diffusion/mel.py +1 -1
- diffusers/pipelines/deprecated/audio_diffusion/pipeline_audio_diffusion.py +3 -3
- diffusers/pipelines/deprecated/latent_diffusion_uncond/pipeline_latent_diffusion_uncond.py +1 -1
- diffusers/pipelines/deprecated/pndm/pipeline_pndm.py +2 -2
- diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +4 -3
- diffusers/pipelines/deprecated/score_sde_ve/pipeline_score_sde_ve.py +1 -1
- diffusers/pipelines/deprecated/spectrogram_diffusion/continuous_encoder.py +1 -1
- diffusers/pipelines/deprecated/spectrogram_diffusion/midi_utils.py +1 -1
- diffusers/pipelines/deprecated/spectrogram_diffusion/notes_encoder.py +1 -1
- diffusers/pipelines/deprecated/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +1 -1
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +7 -7
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_onnx_stable_diffusion_inpaint_legacy.py +9 -9
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +10 -10
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +10 -8
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +5 -5
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +18 -18
- diffusers/pipelines/deprecated/stochastic_karras_ve/pipeline_stochastic_karras_ve.py +1 -1
- diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +2 -2
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py +6 -6
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +5 -5
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +5 -5
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +5 -5
- diffusers/pipelines/deprecated/vq_diffusion/pipeline_vq_diffusion.py +1 -1
- diffusers/pipelines/dit/pipeline_dit.py +1 -1
- diffusers/pipelines/easyanimate/pipeline_easyanimate.py +4 -4
- diffusers/pipelines/easyanimate/pipeline_easyanimate_control.py +4 -4
- diffusers/pipelines/easyanimate/pipeline_easyanimate_inpaint.py +7 -6
- diffusers/pipelines/flux/modeling_flux.py +1 -1
- diffusers/pipelines/flux/pipeline_flux.py +10 -17
- diffusers/pipelines/flux/pipeline_flux_control.py +6 -6
- diffusers/pipelines/flux/pipeline_flux_control_img2img.py +6 -6
- diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +6 -6
- diffusers/pipelines/flux/pipeline_flux_controlnet.py +6 -6
- diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +30 -22
- diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +2 -1
- diffusers/pipelines/flux/pipeline_flux_fill.py +6 -6
- diffusers/pipelines/flux/pipeline_flux_img2img.py +39 -6
- diffusers/pipelines/flux/pipeline_flux_inpaint.py +11 -6
- diffusers/pipelines/flux/pipeline_flux_prior_redux.py +1 -1
- diffusers/pipelines/free_init_utils.py +2 -2
- diffusers/pipelines/free_noise_utils.py +3 -3
- diffusers/pipelines/hidream_image/__init__.py +47 -0
- diffusers/pipelines/hidream_image/pipeline_hidream_image.py +1026 -0
- diffusers/pipelines/hidream_image/pipeline_output.py +35 -0
- diffusers/pipelines/hunyuan_video/__init__.py +2 -0
- diffusers/pipelines/hunyuan_video/pipeline_hunyuan_skyreels_image2video.py +8 -8
- diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +8 -8
- diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video_framepack.py +1114 -0
- diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video_image2video.py +71 -15
- diffusers/pipelines/hunyuan_video/pipeline_output.py +19 -0
- diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +8 -8
- diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +10 -8
- diffusers/pipelines/kandinsky/pipeline_kandinsky.py +6 -6
- diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +34 -34
- diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +19 -26
- diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +7 -7
- diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +11 -11
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +6 -6
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +35 -35
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +6 -6
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +17 -39
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +17 -45
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +7 -7
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +10 -10
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +10 -10
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +7 -7
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +17 -38
- diffusers/pipelines/kolors/pipeline_kolors.py +10 -10
- diffusers/pipelines/kolors/pipeline_kolors_img2img.py +12 -12
- diffusers/pipelines/kolors/text_encoder.py +3 -3
- diffusers/pipelines/kolors/tokenizer.py +1 -1
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +2 -2
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +2 -2
- diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -1
- diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion_superresolution.py +3 -3
- diffusers/pipelines/latte/pipeline_latte.py +12 -12
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +13 -13
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +17 -16
- diffusers/pipelines/ltx/__init__.py +4 -0
- diffusers/pipelines/ltx/modeling_latent_upsampler.py +188 -0
- diffusers/pipelines/ltx/pipeline_ltx.py +51 -6
- diffusers/pipelines/ltx/pipeline_ltx_condition.py +107 -29
- diffusers/pipelines/ltx/pipeline_ltx_image2video.py +50 -6
- diffusers/pipelines/ltx/pipeline_ltx_latent_upsample.py +277 -0
- diffusers/pipelines/lumina/pipeline_lumina.py +13 -13
- diffusers/pipelines/lumina2/pipeline_lumina2.py +10 -10
- diffusers/pipelines/marigold/marigold_image_processing.py +2 -2
- diffusers/pipelines/mochi/pipeline_mochi.py +6 -6
- diffusers/pipelines/musicldm/pipeline_musicldm.py +16 -13
- diffusers/pipelines/omnigen/pipeline_omnigen.py +13 -11
- diffusers/pipelines/omnigen/processor_omnigen.py +8 -3
- diffusers/pipelines/onnx_utils.py +15 -2
- diffusers/pipelines/pag/pag_utils.py +2 -2
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +12 -8
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +7 -7
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +10 -6
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +14 -14
- diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +8 -8
- diffusers/pipelines/pag/pipeline_pag_kolors.py +10 -10
- diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +11 -11
- diffusers/pipelines/pag/pipeline_pag_sana.py +18 -12
- diffusers/pipelines/pag/pipeline_pag_sd.py +8 -8
- diffusers/pipelines/pag/pipeline_pag_sd_3.py +7 -7
- diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +7 -7
- diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +6 -6
- diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +5 -5
- diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +8 -8
- diffusers/pipelines/pag/pipeline_pag_sd_xl.py +16 -15
- diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +18 -17
- diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +12 -12
- diffusers/pipelines/paint_by_example/image_encoder.py +1 -1
- diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +8 -7
- diffusers/pipelines/pia/pipeline_pia.py +8 -6
- diffusers/pipelines/pipeline_flax_utils.py +3 -4
- diffusers/pipelines/pipeline_loading_utils.py +89 -13
- diffusers/pipelines/pipeline_utils.py +105 -33
- diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +11 -11
- diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +11 -11
- diffusers/pipelines/sana/__init__.py +4 -0
- diffusers/pipelines/sana/pipeline_sana.py +23 -21
- diffusers/pipelines/sana/pipeline_sana_controlnet.py +1106 -0
- diffusers/pipelines/sana/pipeline_sana_sprint.py +23 -19
- diffusers/pipelines/sana/pipeline_sana_sprint_img2img.py +981 -0
- diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +7 -6
- diffusers/pipelines/shap_e/camera.py +1 -1
- diffusers/pipelines/shap_e/pipeline_shap_e.py +1 -1
- diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +1 -1
- diffusers/pipelines/shap_e/renderer.py +3 -3
- diffusers/pipelines/stable_audio/modeling_stable_audio.py +1 -1
- diffusers/pipelines/stable_audio/pipeline_stable_audio.py +5 -5
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +8 -8
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +13 -13
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +9 -9
- diffusers/pipelines/stable_diffusion/__init__.py +0 -7
- diffusers/pipelines/stable_diffusion/clip_image_project_model.py +1 -1
- diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +11 -4
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_img2img.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_inpaint.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +10 -10
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +10 -10
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +10 -10
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +9 -9
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +8 -8
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +5 -5
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +5 -5
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +5 -5
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +5 -5
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +5 -5
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +4 -4
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +5 -5
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +7 -7
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +5 -5
- diffusers/pipelines/stable_diffusion/safety_checker.py +1 -1
- diffusers/pipelines/stable_diffusion/safety_checker_flax.py +1 -1
- diffusers/pipelines/stable_diffusion/stable_unclip_image_normalizer.py +1 -1
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +7 -7
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +7 -7
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +7 -7
- diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +12 -8
- diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +15 -9
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +11 -9
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +11 -9
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +18 -12
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +11 -8
- diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +11 -8
- diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +15 -12
- diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +8 -6
- diffusers/pipelines/stable_diffusion_safe/safety_checker.py +1 -1
- diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +15 -11
- diffusers/pipelines/stable_diffusion_xl/pipeline_flax_stable_diffusion_xl.py +1 -1
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +16 -15
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +18 -17
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +12 -12
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +16 -15
- diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +3 -3
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +12 -12
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +18 -17
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +12 -7
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +12 -7
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +15 -13
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +24 -21
- diffusers/pipelines/unclip/pipeline_unclip.py +4 -3
- diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +4 -3
- diffusers/pipelines/unclip/text_proj.py +2 -2
- diffusers/pipelines/unidiffuser/modeling_text_decoder.py +2 -2
- diffusers/pipelines/unidiffuser/modeling_uvit.py +1 -1
- diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +8 -7
- diffusers/pipelines/visualcloze/__init__.py +52 -0
- diffusers/pipelines/visualcloze/pipeline_visualcloze_combined.py +444 -0
- diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py +952 -0
- diffusers/pipelines/visualcloze/visualcloze_utils.py +251 -0
- diffusers/pipelines/wan/__init__.py +2 -0
- diffusers/pipelines/wan/pipeline_wan.py +17 -12
- diffusers/pipelines/wan/pipeline_wan_i2v.py +42 -20
- diffusers/pipelines/wan/pipeline_wan_vace.py +976 -0
- diffusers/pipelines/wan/pipeline_wan_video2video.py +18 -18
- diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +1 -1
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py +1 -1
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +1 -1
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +8 -8
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +16 -15
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +6 -6
- diffusers/quantizers/__init__.py +179 -1
- diffusers/quantizers/base.py +6 -1
- diffusers/quantizers/bitsandbytes/bnb_quantizer.py +4 -0
- diffusers/quantizers/bitsandbytes/utils.py +10 -7
- diffusers/quantizers/gguf/gguf_quantizer.py +13 -4
- diffusers/quantizers/gguf/utils.py +16 -13
- diffusers/quantizers/quantization_config.py +18 -16
- diffusers/quantizers/quanto/quanto_quantizer.py +4 -0
- diffusers/quantizers/torchao/torchao_quantizer.py +5 -1
- diffusers/schedulers/__init__.py +3 -1
- diffusers/schedulers/deprecated/scheduling_karras_ve.py +4 -3
- diffusers/schedulers/deprecated/scheduling_sde_vp.py +1 -1
- diffusers/schedulers/scheduling_consistency_models.py +1 -1
- diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +10 -5
- diffusers/schedulers/scheduling_ddim.py +8 -8
- diffusers/schedulers/scheduling_ddim_cogvideox.py +5 -5
- diffusers/schedulers/scheduling_ddim_flax.py +6 -6
- diffusers/schedulers/scheduling_ddim_inverse.py +6 -6
- diffusers/schedulers/scheduling_ddim_parallel.py +22 -22
- diffusers/schedulers/scheduling_ddpm.py +9 -9
- diffusers/schedulers/scheduling_ddpm_flax.py +7 -7
- diffusers/schedulers/scheduling_ddpm_parallel.py +18 -18
- diffusers/schedulers/scheduling_ddpm_wuerstchen.py +2 -2
- diffusers/schedulers/scheduling_deis_multistep.py +8 -8
- diffusers/schedulers/scheduling_dpm_cogvideox.py +5 -5
- diffusers/schedulers/scheduling_dpmsolver_multistep.py +12 -12
- diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py +22 -20
- diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +11 -11
- diffusers/schedulers/scheduling_dpmsolver_sde.py +2 -2
- diffusers/schedulers/scheduling_dpmsolver_singlestep.py +13 -13
- diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +13 -8
- diffusers/schedulers/scheduling_edm_euler.py +20 -11
- diffusers/schedulers/scheduling_euler_ancestral_discrete.py +3 -3
- diffusers/schedulers/scheduling_euler_discrete.py +3 -3
- diffusers/schedulers/scheduling_euler_discrete_flax.py +3 -3
- diffusers/schedulers/scheduling_flow_match_euler_discrete.py +20 -5
- diffusers/schedulers/scheduling_flow_match_heun_discrete.py +1 -1
- diffusers/schedulers/scheduling_flow_match_lcm.py +561 -0
- diffusers/schedulers/scheduling_heun_discrete.py +2 -2
- diffusers/schedulers/scheduling_ipndm.py +2 -2
- diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +2 -2
- diffusers/schedulers/scheduling_k_dpm_2_discrete.py +2 -2
- diffusers/schedulers/scheduling_karras_ve_flax.py +5 -5
- diffusers/schedulers/scheduling_lcm.py +3 -3
- diffusers/schedulers/scheduling_lms_discrete.py +2 -2
- diffusers/schedulers/scheduling_lms_discrete_flax.py +1 -1
- diffusers/schedulers/scheduling_pndm.py +4 -4
- diffusers/schedulers/scheduling_pndm_flax.py +4 -4
- diffusers/schedulers/scheduling_repaint.py +9 -9
- diffusers/schedulers/scheduling_sasolver.py +15 -15
- diffusers/schedulers/scheduling_scm.py +1 -1
- diffusers/schedulers/scheduling_sde_ve.py +1 -1
- diffusers/schedulers/scheduling_sde_ve_flax.py +2 -2
- diffusers/schedulers/scheduling_tcd.py +3 -3
- diffusers/schedulers/scheduling_unclip.py +5 -5
- diffusers/schedulers/scheduling_unipc_multistep.py +11 -11
- diffusers/schedulers/scheduling_utils.py +1 -1
- diffusers/schedulers/scheduling_utils_flax.py +1 -1
- diffusers/schedulers/scheduling_vq_diffusion.py +1 -1
- diffusers/training_utils.py +13 -5
- diffusers/utils/__init__.py +5 -0
- diffusers/utils/accelerate_utils.py +1 -1
- diffusers/utils/doc_utils.py +1 -1
- diffusers/utils/dummy_pt_objects.py +120 -0
- diffusers/utils/dummy_torch_and_transformers_objects.py +225 -0
- diffusers/utils/dynamic_modules_utils.py +21 -3
- diffusers/utils/export_utils.py +1 -1
- diffusers/utils/import_utils.py +81 -18
- diffusers/utils/logging.py +1 -1
- diffusers/utils/outputs.py +2 -1
- diffusers/utils/peft_utils.py +91 -8
- diffusers/utils/state_dict_utils.py +20 -3
- diffusers/utils/testing_utils.py +59 -7
- diffusers/utils/torch_utils.py +25 -5
- diffusers/video_processor.py +2 -2
- {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/METADATA +3 -3
- diffusers-0.34.0.dist-info/RECORD +639 -0
- diffusers-0.33.0.dist-info/RECORD +0 -608
- {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/LICENSE +0 -0
- {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/WHEEL +0 -0
- {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/entry_points.txt +0 -0
- {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,981 @@
|
|
1
|
+
# Copyright 2025 PixArt-Sigma Authors 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
|
+
|
15
|
+
import html
|
16
|
+
import inspect
|
17
|
+
import re
|
18
|
+
import urllib.parse as ul
|
19
|
+
import warnings
|
20
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
21
|
+
|
22
|
+
import torch
|
23
|
+
import torch.nn.functional as F
|
24
|
+
from transformers import Gemma2PreTrainedModel, GemmaTokenizer, GemmaTokenizerFast
|
25
|
+
|
26
|
+
from ...callbacks import MultiPipelineCallbacks, PipelineCallback
|
27
|
+
from ...image_processor import PipelineImageInput, PixArtImageProcessor
|
28
|
+
from ...loaders import SanaLoraLoaderMixin
|
29
|
+
from ...models import AutoencoderDC, SanaTransformer2DModel
|
30
|
+
from ...schedulers import DPMSolverMultistepScheduler
|
31
|
+
from ...utils import (
|
32
|
+
BACKENDS_MAPPING,
|
33
|
+
USE_PEFT_BACKEND,
|
34
|
+
is_bs4_available,
|
35
|
+
is_ftfy_available,
|
36
|
+
is_torch_xla_available,
|
37
|
+
logging,
|
38
|
+
replace_example_docstring,
|
39
|
+
scale_lora_layers,
|
40
|
+
unscale_lora_layers,
|
41
|
+
)
|
42
|
+
from ...utils.torch_utils import get_device, is_torch_version, randn_tensor
|
43
|
+
from ..pipeline_utils import DiffusionPipeline
|
44
|
+
from ..pixart_alpha.pipeline_pixart_alpha import ASPECT_RATIO_1024_BIN
|
45
|
+
from .pipeline_output import SanaPipelineOutput
|
46
|
+
|
47
|
+
|
48
|
+
if is_torch_xla_available():
|
49
|
+
import torch_xla.core.xla_model as xm
|
50
|
+
|
51
|
+
XLA_AVAILABLE = True
|
52
|
+
else:
|
53
|
+
XLA_AVAILABLE = False
|
54
|
+
|
55
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
56
|
+
|
57
|
+
if is_bs4_available():
|
58
|
+
from bs4 import BeautifulSoup
|
59
|
+
|
60
|
+
if is_ftfy_available():
|
61
|
+
import ftfy
|
62
|
+
|
63
|
+
EXAMPLE_DOC_STRING = """
|
64
|
+
Examples:
|
65
|
+
```py
|
66
|
+
>>> import torch
|
67
|
+
>>> from diffusers import SanaSprintImg2ImgPipeline
|
68
|
+
>>> from diffusers.utils.loading_utils import load_image
|
69
|
+
|
70
|
+
>>> pipe = SanaSprintImg2ImgPipeline.from_pretrained(
|
71
|
+
... "Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers", torch_dtype=torch.bfloat16
|
72
|
+
... )
|
73
|
+
>>> pipe.to("cuda")
|
74
|
+
|
75
|
+
>>> image = load_image(
|
76
|
+
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/penguin.png"
|
77
|
+
... )
|
78
|
+
|
79
|
+
|
80
|
+
>>> image = pipe(prompt="a cute pink bear", image=image, strength=0.5, height=832, width=480).images[0]
|
81
|
+
>>> image[0].save("output.png")
|
82
|
+
```
|
83
|
+
"""
|
84
|
+
|
85
|
+
|
86
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
87
|
+
def retrieve_timesteps(
|
88
|
+
scheduler,
|
89
|
+
num_inference_steps: Optional[int] = None,
|
90
|
+
device: Optional[Union[str, torch.device]] = None,
|
91
|
+
timesteps: Optional[List[int]] = None,
|
92
|
+
sigmas: Optional[List[float]] = None,
|
93
|
+
**kwargs,
|
94
|
+
):
|
95
|
+
r"""
|
96
|
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
97
|
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
98
|
+
|
99
|
+
Args:
|
100
|
+
scheduler (`SchedulerMixin`):
|
101
|
+
The scheduler to get timesteps from.
|
102
|
+
num_inference_steps (`int`):
|
103
|
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
104
|
+
must be `None`.
|
105
|
+
device (`str` or `torch.device`, *optional*):
|
106
|
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
107
|
+
timesteps (`List[int]`, *optional*):
|
108
|
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
109
|
+
`num_inference_steps` and `sigmas` must be `None`.
|
110
|
+
sigmas (`List[float]`, *optional*):
|
111
|
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
112
|
+
`num_inference_steps` and `timesteps` must be `None`.
|
113
|
+
|
114
|
+
Returns:
|
115
|
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
116
|
+
second element is the number of inference steps.
|
117
|
+
"""
|
118
|
+
if timesteps is not None and sigmas is not None:
|
119
|
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
120
|
+
if timesteps is not None:
|
121
|
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
122
|
+
if not accepts_timesteps:
|
123
|
+
raise ValueError(
|
124
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
125
|
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
126
|
+
)
|
127
|
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
128
|
+
timesteps = scheduler.timesteps
|
129
|
+
num_inference_steps = len(timesteps)
|
130
|
+
elif sigmas is not None:
|
131
|
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
132
|
+
if not accept_sigmas:
|
133
|
+
raise ValueError(
|
134
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
135
|
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
136
|
+
)
|
137
|
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
138
|
+
timesteps = scheduler.timesteps
|
139
|
+
num_inference_steps = len(timesteps)
|
140
|
+
else:
|
141
|
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
142
|
+
timesteps = scheduler.timesteps
|
143
|
+
return timesteps, num_inference_steps
|
144
|
+
|
145
|
+
|
146
|
+
class SanaSprintImg2ImgPipeline(DiffusionPipeline, SanaLoraLoaderMixin):
|
147
|
+
r"""
|
148
|
+
Pipeline for text-to-image generation using [SANA-Sprint](https://huggingface.co/papers/2503.09641).
|
149
|
+
"""
|
150
|
+
|
151
|
+
# fmt: off
|
152
|
+
bad_punct_regex = re.compile(
|
153
|
+
r"[" + "#®•©™&@·º½¾¿¡§~" + r"\)" + r"\(" + r"\]" + r"\[" + r"\}" + r"\{" + r"\|" + "\\" + r"\/" + r"\*" + r"]{1,}")
|
154
|
+
# fmt: on
|
155
|
+
|
156
|
+
model_cpu_offload_seq = "text_encoder->transformer->vae"
|
157
|
+
_callback_tensor_inputs = ["latents", "prompt_embeds"]
|
158
|
+
|
159
|
+
def __init__(
|
160
|
+
self,
|
161
|
+
tokenizer: Union[GemmaTokenizer, GemmaTokenizerFast],
|
162
|
+
text_encoder: Gemma2PreTrainedModel,
|
163
|
+
vae: AutoencoderDC,
|
164
|
+
transformer: SanaTransformer2DModel,
|
165
|
+
scheduler: DPMSolverMultistepScheduler,
|
166
|
+
):
|
167
|
+
super().__init__()
|
168
|
+
|
169
|
+
self.register_modules(
|
170
|
+
tokenizer=tokenizer, text_encoder=text_encoder, vae=vae, transformer=transformer, scheduler=scheduler
|
171
|
+
)
|
172
|
+
|
173
|
+
self.vae_scale_factor = (
|
174
|
+
2 ** (len(self.vae.config.encoder_block_out_channels) - 1)
|
175
|
+
if hasattr(self, "vae") and self.vae is not None
|
176
|
+
else 32
|
177
|
+
)
|
178
|
+
self.image_processor = PixArtImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
179
|
+
|
180
|
+
# Copied from diffusers.pipelines.sana.pipeline_sana.SanaPipeline.enable_vae_slicing
|
181
|
+
def enable_vae_slicing(self):
|
182
|
+
r"""
|
183
|
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
184
|
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
185
|
+
"""
|
186
|
+
self.vae.enable_slicing()
|
187
|
+
|
188
|
+
# Copied from diffusers.pipelines.sana.pipeline_sana.SanaPipeline.disable_vae_slicing
|
189
|
+
def disable_vae_slicing(self):
|
190
|
+
r"""
|
191
|
+
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
|
192
|
+
computing decoding in one step.
|
193
|
+
"""
|
194
|
+
self.vae.disable_slicing()
|
195
|
+
|
196
|
+
# Copied from diffusers.pipelines.sana.pipeline_sana.SanaPipeline.enable_vae_tiling
|
197
|
+
def enable_vae_tiling(self):
|
198
|
+
r"""
|
199
|
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
200
|
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
201
|
+
processing larger images.
|
202
|
+
"""
|
203
|
+
self.vae.enable_tiling()
|
204
|
+
|
205
|
+
def disable_vae_tiling(self):
|
206
|
+
r"""
|
207
|
+
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
|
208
|
+
computing decoding in one step.
|
209
|
+
"""
|
210
|
+
self.vae.disable_tiling()
|
211
|
+
|
212
|
+
# Copied from diffusers.pipelines.sana.pipeline_sana.SanaPipeline._get_gemma_prompt_embeds
|
213
|
+
def _get_gemma_prompt_embeds(
|
214
|
+
self,
|
215
|
+
prompt: Union[str, List[str]],
|
216
|
+
device: torch.device,
|
217
|
+
dtype: torch.dtype,
|
218
|
+
clean_caption: bool = False,
|
219
|
+
max_sequence_length: int = 300,
|
220
|
+
complex_human_instruction: Optional[List[str]] = None,
|
221
|
+
):
|
222
|
+
r"""
|
223
|
+
Encodes the prompt into text encoder hidden states.
|
224
|
+
|
225
|
+
Args:
|
226
|
+
prompt (`str` or `List[str]`, *optional*):
|
227
|
+
prompt to be encoded
|
228
|
+
device: (`torch.device`, *optional*):
|
229
|
+
torch device to place the resulting embeddings on
|
230
|
+
clean_caption (`bool`, defaults to `False`):
|
231
|
+
If `True`, the function will preprocess and clean the provided caption before encoding.
|
232
|
+
max_sequence_length (`int`, defaults to 300): Maximum sequence length to use for the prompt.
|
233
|
+
complex_human_instruction (`list[str]`, defaults to `complex_human_instruction`):
|
234
|
+
If `complex_human_instruction` is not empty, the function will use the complex Human instruction for
|
235
|
+
the prompt.
|
236
|
+
"""
|
237
|
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
238
|
+
|
239
|
+
if getattr(self, "tokenizer", None) is not None:
|
240
|
+
self.tokenizer.padding_side = "right"
|
241
|
+
|
242
|
+
prompt = self._text_preprocessing(prompt, clean_caption=clean_caption)
|
243
|
+
|
244
|
+
# prepare complex human instruction
|
245
|
+
if not complex_human_instruction:
|
246
|
+
max_length_all = max_sequence_length
|
247
|
+
else:
|
248
|
+
chi_prompt = "\n".join(complex_human_instruction)
|
249
|
+
prompt = [chi_prompt + p for p in prompt]
|
250
|
+
num_chi_prompt_tokens = len(self.tokenizer.encode(chi_prompt))
|
251
|
+
max_length_all = num_chi_prompt_tokens + max_sequence_length - 2
|
252
|
+
|
253
|
+
text_inputs = self.tokenizer(
|
254
|
+
prompt,
|
255
|
+
padding="max_length",
|
256
|
+
max_length=max_length_all,
|
257
|
+
truncation=True,
|
258
|
+
add_special_tokens=True,
|
259
|
+
return_tensors="pt",
|
260
|
+
)
|
261
|
+
text_input_ids = text_inputs.input_ids
|
262
|
+
|
263
|
+
prompt_attention_mask = text_inputs.attention_mask
|
264
|
+
prompt_attention_mask = prompt_attention_mask.to(device)
|
265
|
+
|
266
|
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=prompt_attention_mask)
|
267
|
+
prompt_embeds = prompt_embeds[0].to(dtype=dtype, device=device)
|
268
|
+
|
269
|
+
return prompt_embeds, prompt_attention_mask
|
270
|
+
|
271
|
+
# Copied from diffusers.pipelines.sana.pipeline_sana_sprint.SanaSprintPipeline.encode_prompt
|
272
|
+
def encode_prompt(
|
273
|
+
self,
|
274
|
+
prompt: Union[str, List[str]],
|
275
|
+
num_images_per_prompt: int = 1,
|
276
|
+
device: Optional[torch.device] = None,
|
277
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
278
|
+
prompt_attention_mask: Optional[torch.Tensor] = None,
|
279
|
+
clean_caption: bool = False,
|
280
|
+
max_sequence_length: int = 300,
|
281
|
+
complex_human_instruction: Optional[List[str]] = None,
|
282
|
+
lora_scale: Optional[float] = None,
|
283
|
+
):
|
284
|
+
r"""
|
285
|
+
Encodes the prompt into text encoder hidden states.
|
286
|
+
|
287
|
+
Args:
|
288
|
+
prompt (`str` or `List[str]`, *optional*):
|
289
|
+
prompt to be encoded
|
290
|
+
|
291
|
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
292
|
+
number of images that should be generated per prompt
|
293
|
+
device: (`torch.device`, *optional*):
|
294
|
+
torch device to place the resulting embeddings on
|
295
|
+
prompt_embeds (`torch.Tensor`, *optional*):
|
296
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
297
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
298
|
+
clean_caption (`bool`, defaults to `False`):
|
299
|
+
If `True`, the function will preprocess and clean the provided caption before encoding.
|
300
|
+
max_sequence_length (`int`, defaults to 300): Maximum sequence length to use for the prompt.
|
301
|
+
complex_human_instruction (`list[str]`, defaults to `complex_human_instruction`):
|
302
|
+
If `complex_human_instruction` is not empty, the function will use the complex Human instruction for
|
303
|
+
the prompt.
|
304
|
+
"""
|
305
|
+
|
306
|
+
if device is None:
|
307
|
+
device = self._execution_device
|
308
|
+
|
309
|
+
if self.text_encoder is not None:
|
310
|
+
dtype = self.text_encoder.dtype
|
311
|
+
else:
|
312
|
+
dtype = None
|
313
|
+
|
314
|
+
# set lora scale so that monkey patched LoRA
|
315
|
+
# function of text encoder can correctly access it
|
316
|
+
if lora_scale is not None and isinstance(self, SanaLoraLoaderMixin):
|
317
|
+
self._lora_scale = lora_scale
|
318
|
+
|
319
|
+
# dynamically adjust the LoRA scale
|
320
|
+
if self.text_encoder is not None and USE_PEFT_BACKEND:
|
321
|
+
scale_lora_layers(self.text_encoder, lora_scale)
|
322
|
+
|
323
|
+
if getattr(self, "tokenizer", None) is not None:
|
324
|
+
self.tokenizer.padding_side = "right"
|
325
|
+
|
326
|
+
# See Section 3.1. of the paper.
|
327
|
+
max_length = max_sequence_length
|
328
|
+
select_index = [0] + list(range(-max_length + 1, 0))
|
329
|
+
|
330
|
+
if prompt_embeds is None:
|
331
|
+
prompt_embeds, prompt_attention_mask = self._get_gemma_prompt_embeds(
|
332
|
+
prompt=prompt,
|
333
|
+
device=device,
|
334
|
+
dtype=dtype,
|
335
|
+
clean_caption=clean_caption,
|
336
|
+
max_sequence_length=max_sequence_length,
|
337
|
+
complex_human_instruction=complex_human_instruction,
|
338
|
+
)
|
339
|
+
|
340
|
+
prompt_embeds = prompt_embeds[:, select_index]
|
341
|
+
prompt_attention_mask = prompt_attention_mask[:, select_index]
|
342
|
+
|
343
|
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
344
|
+
# duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
|
345
|
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
346
|
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
347
|
+
prompt_attention_mask = prompt_attention_mask.view(bs_embed, -1)
|
348
|
+
prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)
|
349
|
+
|
350
|
+
if self.text_encoder is not None:
|
351
|
+
if isinstance(self, SanaLoraLoaderMixin) and USE_PEFT_BACKEND:
|
352
|
+
# Retrieve the original scale by scaling back the LoRA layers
|
353
|
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
354
|
+
|
355
|
+
return prompt_embeds, prompt_attention_mask
|
356
|
+
|
357
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
358
|
+
def prepare_extra_step_kwargs(self, generator, eta):
|
359
|
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
360
|
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
361
|
+
# eta corresponds to η in DDIM paper: https://huggingface.co/papers/2010.02502
|
362
|
+
# and should be between [0, 1]
|
363
|
+
|
364
|
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
365
|
+
extra_step_kwargs = {}
|
366
|
+
if accepts_eta:
|
367
|
+
extra_step_kwargs["eta"] = eta
|
368
|
+
|
369
|
+
# check if the scheduler accepts generator
|
370
|
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
371
|
+
if accepts_generator:
|
372
|
+
extra_step_kwargs["generator"] = generator
|
373
|
+
return extra_step_kwargs
|
374
|
+
|
375
|
+
# Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_img2img.StableDiffusion3Img2ImgPipeline.get_timesteps
|
376
|
+
def get_timesteps(self, num_inference_steps, strength, device):
|
377
|
+
# get the original timestep using init_timestep
|
378
|
+
init_timestep = min(num_inference_steps * strength, num_inference_steps)
|
379
|
+
|
380
|
+
t_start = int(max(num_inference_steps - init_timestep, 0))
|
381
|
+
timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
|
382
|
+
if hasattr(self.scheduler, "set_begin_index"):
|
383
|
+
self.scheduler.set_begin_index(t_start * self.scheduler.order)
|
384
|
+
|
385
|
+
return timesteps, num_inference_steps - t_start
|
386
|
+
|
387
|
+
def check_inputs(
|
388
|
+
self,
|
389
|
+
prompt,
|
390
|
+
strength,
|
391
|
+
height,
|
392
|
+
width,
|
393
|
+
num_inference_steps,
|
394
|
+
timesteps,
|
395
|
+
max_timesteps,
|
396
|
+
intermediate_timesteps,
|
397
|
+
callback_on_step_end_tensor_inputs=None,
|
398
|
+
prompt_embeds=None,
|
399
|
+
prompt_attention_mask=None,
|
400
|
+
):
|
401
|
+
if strength < 0 or strength > 1:
|
402
|
+
raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
|
403
|
+
|
404
|
+
if height % 32 != 0 or width % 32 != 0:
|
405
|
+
raise ValueError(f"`height` and `width` have to be divisible by 32 but are {height} and {width}.")
|
406
|
+
|
407
|
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
408
|
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
409
|
+
):
|
410
|
+
raise ValueError(
|
411
|
+
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]}"
|
412
|
+
)
|
413
|
+
|
414
|
+
if prompt is not None and prompt_embeds is not None:
|
415
|
+
raise ValueError(
|
416
|
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
417
|
+
" only forward one of the two."
|
418
|
+
)
|
419
|
+
elif prompt is None and prompt_embeds is None:
|
420
|
+
raise ValueError(
|
421
|
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
422
|
+
)
|
423
|
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
424
|
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
425
|
+
|
426
|
+
if prompt_embeds is not None and prompt_attention_mask is None:
|
427
|
+
raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.")
|
428
|
+
|
429
|
+
if timesteps is not None and len(timesteps) != num_inference_steps + 1:
|
430
|
+
raise ValueError("If providing custom timesteps, `timesteps` must be of length `num_inference_steps + 1`.")
|
431
|
+
|
432
|
+
if timesteps is not None and max_timesteps is not None:
|
433
|
+
raise ValueError("If providing custom timesteps, `max_timesteps` should not be provided.")
|
434
|
+
|
435
|
+
if timesteps is None and max_timesteps is None:
|
436
|
+
raise ValueError("Should provide either `timesteps` or `max_timesteps`.")
|
437
|
+
|
438
|
+
if intermediate_timesteps is not None and num_inference_steps != 2:
|
439
|
+
raise ValueError("Intermediate timesteps for SCM is not supported when num_inference_steps != 2.")
|
440
|
+
|
441
|
+
# Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._text_preprocessing
|
442
|
+
def _text_preprocessing(self, text, clean_caption=False):
|
443
|
+
if clean_caption and not is_bs4_available():
|
444
|
+
logger.warning(BACKENDS_MAPPING["bs4"][-1].format("Setting `clean_caption=True`"))
|
445
|
+
logger.warning("Setting `clean_caption` to False...")
|
446
|
+
clean_caption = False
|
447
|
+
|
448
|
+
if clean_caption and not is_ftfy_available():
|
449
|
+
logger.warning(BACKENDS_MAPPING["ftfy"][-1].format("Setting `clean_caption=True`"))
|
450
|
+
logger.warning("Setting `clean_caption` to False...")
|
451
|
+
clean_caption = False
|
452
|
+
|
453
|
+
if not isinstance(text, (tuple, list)):
|
454
|
+
text = [text]
|
455
|
+
|
456
|
+
def process(text: str):
|
457
|
+
if clean_caption:
|
458
|
+
text = self._clean_caption(text)
|
459
|
+
text = self._clean_caption(text)
|
460
|
+
else:
|
461
|
+
text = text.lower().strip()
|
462
|
+
return text
|
463
|
+
|
464
|
+
return [process(t) for t in text]
|
465
|
+
|
466
|
+
# Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._clean_caption
|
467
|
+
def _clean_caption(self, caption):
|
468
|
+
caption = str(caption)
|
469
|
+
caption = ul.unquote_plus(caption)
|
470
|
+
caption = caption.strip().lower()
|
471
|
+
caption = re.sub("<person>", "person", caption)
|
472
|
+
# urls:
|
473
|
+
caption = re.sub(
|
474
|
+
r"\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa
|
475
|
+
"",
|
476
|
+
caption,
|
477
|
+
) # regex for urls
|
478
|
+
caption = re.sub(
|
479
|
+
r"\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa
|
480
|
+
"",
|
481
|
+
caption,
|
482
|
+
) # regex for urls
|
483
|
+
# html:
|
484
|
+
caption = BeautifulSoup(caption, features="html.parser").text
|
485
|
+
|
486
|
+
# @<nickname>
|
487
|
+
caption = re.sub(r"@[\w\d]+\b", "", caption)
|
488
|
+
|
489
|
+
# 31C0—31EF CJK Strokes
|
490
|
+
# 31F0—31FF Katakana Phonetic Extensions
|
491
|
+
# 3200—32FF Enclosed CJK Letters and Months
|
492
|
+
# 3300—33FF CJK Compatibility
|
493
|
+
# 3400—4DBF CJK Unified Ideographs Extension A
|
494
|
+
# 4DC0—4DFF Yijing Hexagram Symbols
|
495
|
+
# 4E00—9FFF CJK Unified Ideographs
|
496
|
+
caption = re.sub(r"[\u31c0-\u31ef]+", "", caption)
|
497
|
+
caption = re.sub(r"[\u31f0-\u31ff]+", "", caption)
|
498
|
+
caption = re.sub(r"[\u3200-\u32ff]+", "", caption)
|
499
|
+
caption = re.sub(r"[\u3300-\u33ff]+", "", caption)
|
500
|
+
caption = re.sub(r"[\u3400-\u4dbf]+", "", caption)
|
501
|
+
caption = re.sub(r"[\u4dc0-\u4dff]+", "", caption)
|
502
|
+
caption = re.sub(r"[\u4e00-\u9fff]+", "", caption)
|
503
|
+
#######################################################
|
504
|
+
|
505
|
+
# все виды тире / all types of dash --> "-"
|
506
|
+
caption = re.sub(
|
507
|
+
r"[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+", # noqa
|
508
|
+
"-",
|
509
|
+
caption,
|
510
|
+
)
|
511
|
+
|
512
|
+
# кавычки к одному стандарту
|
513
|
+
caption = re.sub(r"[`´«»“”¨]", '"', caption)
|
514
|
+
caption = re.sub(r"[‘’]", "'", caption)
|
515
|
+
|
516
|
+
# "
|
517
|
+
caption = re.sub(r""?", "", caption)
|
518
|
+
# &
|
519
|
+
caption = re.sub(r"&", "", caption)
|
520
|
+
|
521
|
+
# ip addresses:
|
522
|
+
caption = re.sub(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", " ", caption)
|
523
|
+
|
524
|
+
# article ids:
|
525
|
+
caption = re.sub(r"\d:\d\d\s+$", "", caption)
|
526
|
+
|
527
|
+
# \n
|
528
|
+
caption = re.sub(r"\\n", " ", caption)
|
529
|
+
|
530
|
+
# "#123"
|
531
|
+
caption = re.sub(r"#\d{1,3}\b", "", caption)
|
532
|
+
# "#12345.."
|
533
|
+
caption = re.sub(r"#\d{5,}\b", "", caption)
|
534
|
+
# "123456.."
|
535
|
+
caption = re.sub(r"\b\d{6,}\b", "", caption)
|
536
|
+
# filenames:
|
537
|
+
caption = re.sub(r"[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)", "", caption)
|
538
|
+
|
539
|
+
#
|
540
|
+
caption = re.sub(r"[\"\']{2,}", r'"', caption) # """AUSVERKAUFT"""
|
541
|
+
caption = re.sub(r"[\.]{2,}", r" ", caption) # """AUSVERKAUFT"""
|
542
|
+
|
543
|
+
caption = re.sub(self.bad_punct_regex, r" ", caption) # ***AUSVERKAUFT***, #AUSVERKAUFT
|
544
|
+
caption = re.sub(r"\s+\.\s+", r" ", caption) # " . "
|
545
|
+
|
546
|
+
# this-is-my-cute-cat / this_is_my_cute_cat
|
547
|
+
regex2 = re.compile(r"(?:\-|\_)")
|
548
|
+
if len(re.findall(regex2, caption)) > 3:
|
549
|
+
caption = re.sub(regex2, " ", caption)
|
550
|
+
|
551
|
+
caption = ftfy.fix_text(caption)
|
552
|
+
caption = html.unescape(html.unescape(caption))
|
553
|
+
|
554
|
+
caption = re.sub(r"\b[a-zA-Z]{1,3}\d{3,15}\b", "", caption) # jc6640
|
555
|
+
caption = re.sub(r"\b[a-zA-Z]+\d+[a-zA-Z]+\b", "", caption) # jc6640vc
|
556
|
+
caption = re.sub(r"\b\d+[a-zA-Z]+\d+\b", "", caption) # 6640vc231
|
557
|
+
|
558
|
+
caption = re.sub(r"(worldwide\s+)?(free\s+)?shipping", "", caption)
|
559
|
+
caption = re.sub(r"(free\s)?download(\sfree)?", "", caption)
|
560
|
+
caption = re.sub(r"\bclick\b\s(?:for|on)\s\w+", "", caption)
|
561
|
+
caption = re.sub(r"\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?", "", caption)
|
562
|
+
caption = re.sub(r"\bpage\s+\d+\b", "", caption)
|
563
|
+
|
564
|
+
caption = re.sub(r"\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\b", r" ", caption) # j2d1a2a...
|
565
|
+
|
566
|
+
caption = re.sub(r"\b\d+\.?\d*[xх×]\d+\.?\d*\b", "", caption)
|
567
|
+
|
568
|
+
caption = re.sub(r"\b\s+\:\s+", r": ", caption)
|
569
|
+
caption = re.sub(r"(\D[,\./])\b", r"\1 ", caption)
|
570
|
+
caption = re.sub(r"\s+", " ", caption)
|
571
|
+
|
572
|
+
caption.strip()
|
573
|
+
|
574
|
+
caption = re.sub(r"^[\"\']([\w\W]+)[\"\']$", r"\1", caption)
|
575
|
+
caption = re.sub(r"^[\'\_,\-\:;]", r"", caption)
|
576
|
+
caption = re.sub(r"[\'\_,\-\:\-\+]$", r"", caption)
|
577
|
+
caption = re.sub(r"^\.\S+$", "", caption)
|
578
|
+
|
579
|
+
return caption.strip()
|
580
|
+
|
581
|
+
def prepare_image(
|
582
|
+
self,
|
583
|
+
image: PipelineImageInput,
|
584
|
+
width: int,
|
585
|
+
height: int,
|
586
|
+
device: torch.device,
|
587
|
+
dtype: torch.dtype,
|
588
|
+
):
|
589
|
+
if isinstance(image, torch.Tensor):
|
590
|
+
if image.ndim == 3:
|
591
|
+
image = image.unsqueeze(0)
|
592
|
+
# Resize if current dimensions do not match target dimensions.
|
593
|
+
if image.shape[2] != height or image.shape[3] != width:
|
594
|
+
image = F.interpolate(image, size=(height, width), mode="bilinear", align_corners=False)
|
595
|
+
|
596
|
+
image = self.image_processor.preprocess(image, height=height, width=width)
|
597
|
+
|
598
|
+
else:
|
599
|
+
image = self.image_processor.preprocess(image, height=height, width=width)
|
600
|
+
|
601
|
+
image = image.to(device=device, dtype=dtype)
|
602
|
+
|
603
|
+
return image
|
604
|
+
|
605
|
+
def prepare_latents(
|
606
|
+
self, image, timestep, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None
|
607
|
+
):
|
608
|
+
if latents is not None:
|
609
|
+
return latents.to(device=device, dtype=dtype)
|
610
|
+
|
611
|
+
shape = (
|
612
|
+
batch_size,
|
613
|
+
num_channels_latents,
|
614
|
+
int(height) // self.vae_scale_factor,
|
615
|
+
int(width) // self.vae_scale_factor,
|
616
|
+
)
|
617
|
+
|
618
|
+
if image.shape[1] != num_channels_latents:
|
619
|
+
image = self.vae.encode(image).latent
|
620
|
+
image_latents = image * self.vae.config.scaling_factor * self.scheduler.config.sigma_data
|
621
|
+
else:
|
622
|
+
image_latents = image
|
623
|
+
if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
|
624
|
+
# expand init_latents for batch_size
|
625
|
+
additional_image_per_prompt = batch_size // image_latents.shape[0]
|
626
|
+
image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0)
|
627
|
+
elif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] != 0:
|
628
|
+
raise ValueError(
|
629
|
+
f"Cannot duplicate `image` of batch size {image_latents.shape[0]} to {batch_size} text prompts."
|
630
|
+
)
|
631
|
+
else:
|
632
|
+
image_latents = torch.cat([image_latents], dim=0)
|
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
|
+
# adapt from https://github.com/huggingface/diffusers/blob/c36f8487df35895421c15f351c7d360bd680[…]/examples/research_projects/sana/train_sana_sprint_diffusers.py
|
641
|
+
noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype) * self.scheduler.config.sigma_data
|
642
|
+
latents = torch.cos(timestep) * image_latents + torch.sin(timestep) * noise
|
643
|
+
return latents
|
644
|
+
|
645
|
+
@property
|
646
|
+
def guidance_scale(self):
|
647
|
+
return self._guidance_scale
|
648
|
+
|
649
|
+
@property
|
650
|
+
def attention_kwargs(self):
|
651
|
+
return self._attention_kwargs
|
652
|
+
|
653
|
+
@property
|
654
|
+
def num_timesteps(self):
|
655
|
+
return self._num_timesteps
|
656
|
+
|
657
|
+
@property
|
658
|
+
def interrupt(self):
|
659
|
+
return self._interrupt
|
660
|
+
|
661
|
+
@torch.no_grad()
|
662
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
663
|
+
def __call__(
|
664
|
+
self,
|
665
|
+
prompt: Union[str, List[str]] = None,
|
666
|
+
num_inference_steps: int = 2,
|
667
|
+
timesteps: List[int] = None,
|
668
|
+
max_timesteps: float = 1.57080,
|
669
|
+
intermediate_timesteps: float = 1.3,
|
670
|
+
guidance_scale: float = 4.5,
|
671
|
+
image: PipelineImageInput = None,
|
672
|
+
strength: float = 0.6,
|
673
|
+
num_images_per_prompt: Optional[int] = 1,
|
674
|
+
height: int = 1024,
|
675
|
+
width: int = 1024,
|
676
|
+
eta: float = 0.0,
|
677
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
678
|
+
latents: Optional[torch.Tensor] = None,
|
679
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
680
|
+
prompt_attention_mask: Optional[torch.Tensor] = None,
|
681
|
+
output_type: Optional[str] = "pil",
|
682
|
+
return_dict: bool = True,
|
683
|
+
clean_caption: bool = False,
|
684
|
+
use_resolution_binning: bool = True,
|
685
|
+
attention_kwargs: Optional[Dict[str, Any]] = None,
|
686
|
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
687
|
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
688
|
+
max_sequence_length: int = 300,
|
689
|
+
complex_human_instruction: List[str] = [
|
690
|
+
"Given a user prompt, generate an 'Enhanced prompt' that provides detailed visual descriptions suitable for image generation. Evaluate the level of detail in the user prompt:",
|
691
|
+
"- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, and spatial relationships to create vivid and concrete scenes.",
|
692
|
+
"- If the prompt is already detailed, refine and enhance the existing details slightly without overcomplicating.",
|
693
|
+
"Here are examples of how to transform or refine prompts:",
|
694
|
+
"- User Prompt: A cat sleeping -> Enhanced: A small, fluffy white cat curled up in a round shape, sleeping peacefully on a warm sunny windowsill, surrounded by pots of blooming red flowers.",
|
695
|
+
"- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps, a diverse crowd of people in colorful clothing, and a double-decker bus passing by towering glass skyscrapers.",
|
696
|
+
"Please generate only the enhanced description for the prompt below and avoid including any additional commentary or evaluations:",
|
697
|
+
"User Prompt: ",
|
698
|
+
],
|
699
|
+
) -> Union[SanaPipelineOutput, Tuple]:
|
700
|
+
"""
|
701
|
+
Function invoked when calling the pipeline for generation.
|
702
|
+
|
703
|
+
Args:
|
704
|
+
prompt (`str` or `List[str]`, *optional*):
|
705
|
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
706
|
+
instead.
|
707
|
+
num_inference_steps (`int`, *optional*, defaults to 20):
|
708
|
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
709
|
+
expense of slower inference.
|
710
|
+
max_timesteps (`float`, *optional*, defaults to 1.57080):
|
711
|
+
The maximum timestep value used in the SCM scheduler.
|
712
|
+
intermediate_timesteps (`float`, *optional*, defaults to 1.3):
|
713
|
+
The intermediate timestep value used in SCM scheduler (only used when num_inference_steps=2).
|
714
|
+
timesteps (`List[int]`, *optional*):
|
715
|
+
Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
|
716
|
+
in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
|
717
|
+
passed will be used. Must be in descending order.
|
718
|
+
guidance_scale (`float`, *optional*, defaults to 4.5):
|
719
|
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
720
|
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
721
|
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
722
|
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
723
|
+
usually at the expense of lower image quality.
|
724
|
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
725
|
+
The number of images to generate per prompt.
|
726
|
+
height (`int`, *optional*, defaults to self.unet.config.sample_size):
|
727
|
+
The height in pixels of the generated image.
|
728
|
+
width (`int`, *optional*, defaults to self.unet.config.sample_size):
|
729
|
+
The width in pixels of the generated image.
|
730
|
+
eta (`float`, *optional*, defaults to 0.0):
|
731
|
+
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
732
|
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
733
|
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
734
|
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
735
|
+
to make generation deterministic.
|
736
|
+
latents (`torch.Tensor`, *optional*):
|
737
|
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
738
|
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
739
|
+
tensor will ge generated by sampling using the supplied random `generator`.
|
740
|
+
prompt_embeds (`torch.Tensor`, *optional*):
|
741
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
742
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
743
|
+
prompt_attention_mask (`torch.Tensor`, *optional*): Pre-generated attention mask for text embeddings.
|
744
|
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
745
|
+
The output format of the generate image. Choose between
|
746
|
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
747
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
748
|
+
Whether or not to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
|
749
|
+
attention_kwargs:
|
750
|
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
751
|
+
`self.processor` in
|
752
|
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
753
|
+
clean_caption (`bool`, *optional*, defaults to `True`):
|
754
|
+
Whether or not to clean the caption before creating embeddings. Requires `beautifulsoup4` and `ftfy` to
|
755
|
+
be installed. If the dependencies are not installed, the embeddings will be created from the raw
|
756
|
+
prompt.
|
757
|
+
use_resolution_binning (`bool` defaults to `True`):
|
758
|
+
If set to `True`, the requested height and width are first mapped to the closest resolutions using
|
759
|
+
`ASPECT_RATIO_1024_BIN`. After the produced latents are decoded into images, they are resized back to
|
760
|
+
the requested resolution. Useful for generating non-square images.
|
761
|
+
callback_on_step_end (`Callable`, *optional*):
|
762
|
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
763
|
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
764
|
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
765
|
+
`callback_on_step_end_tensor_inputs`.
|
766
|
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
767
|
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
768
|
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
769
|
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
770
|
+
max_sequence_length (`int` defaults to `300`):
|
771
|
+
Maximum sequence length to use with the `prompt`.
|
772
|
+
complex_human_instruction (`List[str]`, *optional*):
|
773
|
+
Instructions for complex human attention:
|
774
|
+
https://github.com/NVlabs/Sana/blob/main/configs/sana_app_config/Sana_1600M_app.yaml#L55.
|
775
|
+
|
776
|
+
Examples:
|
777
|
+
|
778
|
+
Returns:
|
779
|
+
[`~pipelines.sana.pipeline_output.SanaPipelineOutput`] or `tuple`:
|
780
|
+
If `return_dict` is `True`, [`~pipelines.sana.pipeline_output.SanaPipelineOutput`] is returned,
|
781
|
+
otherwise a `tuple` is returned where the first element is a list with the generated images
|
782
|
+
"""
|
783
|
+
|
784
|
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
785
|
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
786
|
+
|
787
|
+
# 1. Check inputs. Raise error if not correct
|
788
|
+
if use_resolution_binning:
|
789
|
+
if self.transformer.config.sample_size == 32:
|
790
|
+
aspect_ratio_bin = ASPECT_RATIO_1024_BIN
|
791
|
+
else:
|
792
|
+
raise ValueError("Invalid sample size")
|
793
|
+
orig_height, orig_width = height, width
|
794
|
+
height, width = self.image_processor.classify_height_width_bin(height, width, ratios=aspect_ratio_bin)
|
795
|
+
|
796
|
+
self.check_inputs(
|
797
|
+
prompt=prompt,
|
798
|
+
strength=strength,
|
799
|
+
height=height,
|
800
|
+
width=width,
|
801
|
+
num_inference_steps=num_inference_steps,
|
802
|
+
timesteps=timesteps,
|
803
|
+
max_timesteps=max_timesteps,
|
804
|
+
intermediate_timesteps=intermediate_timesteps,
|
805
|
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
806
|
+
prompt_embeds=prompt_embeds,
|
807
|
+
prompt_attention_mask=prompt_attention_mask,
|
808
|
+
)
|
809
|
+
|
810
|
+
self._guidance_scale = guidance_scale
|
811
|
+
self._attention_kwargs = attention_kwargs
|
812
|
+
self._interrupt = False
|
813
|
+
|
814
|
+
# 2. Default height and width to transformer
|
815
|
+
if prompt is not None and isinstance(prompt, str):
|
816
|
+
batch_size = 1
|
817
|
+
elif prompt is not None and isinstance(prompt, list):
|
818
|
+
batch_size = len(prompt)
|
819
|
+
else:
|
820
|
+
batch_size = prompt_embeds.shape[0]
|
821
|
+
|
822
|
+
device = self._execution_device
|
823
|
+
lora_scale = self.attention_kwargs.get("scale", None) if self.attention_kwargs is not None else None
|
824
|
+
|
825
|
+
# 2. Preprocess image
|
826
|
+
init_image = self.prepare_image(image, width, height, device, self.vae.dtype)
|
827
|
+
|
828
|
+
# 3. Encode input prompt
|
829
|
+
(
|
830
|
+
prompt_embeds,
|
831
|
+
prompt_attention_mask,
|
832
|
+
) = self.encode_prompt(
|
833
|
+
prompt,
|
834
|
+
num_images_per_prompt=num_images_per_prompt,
|
835
|
+
device=device,
|
836
|
+
prompt_embeds=prompt_embeds,
|
837
|
+
prompt_attention_mask=prompt_attention_mask,
|
838
|
+
clean_caption=clean_caption,
|
839
|
+
max_sequence_length=max_sequence_length,
|
840
|
+
complex_human_instruction=complex_human_instruction,
|
841
|
+
lora_scale=lora_scale,
|
842
|
+
)
|
843
|
+
|
844
|
+
# 5. Prepare timesteps
|
845
|
+
timesteps, num_inference_steps = retrieve_timesteps(
|
846
|
+
self.scheduler,
|
847
|
+
num_inference_steps,
|
848
|
+
device,
|
849
|
+
timesteps,
|
850
|
+
sigmas=None,
|
851
|
+
max_timesteps=max_timesteps,
|
852
|
+
intermediate_timesteps=intermediate_timesteps,
|
853
|
+
)
|
854
|
+
if hasattr(self.scheduler, "set_begin_index"):
|
855
|
+
self.scheduler.set_begin_index(0)
|
856
|
+
|
857
|
+
timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
|
858
|
+
if num_inference_steps < 1:
|
859
|
+
raise ValueError(
|
860
|
+
f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
|
861
|
+
f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
|
862
|
+
)
|
863
|
+
latent_timestep = timesteps[:1]
|
864
|
+
|
865
|
+
# 5. Prepare latents.
|
866
|
+
latent_channels = self.transformer.config.in_channels
|
867
|
+
latents = self.prepare_latents(
|
868
|
+
init_image,
|
869
|
+
latent_timestep,
|
870
|
+
batch_size * num_images_per_prompt,
|
871
|
+
latent_channels,
|
872
|
+
height,
|
873
|
+
width,
|
874
|
+
torch.float32,
|
875
|
+
device,
|
876
|
+
generator,
|
877
|
+
latents,
|
878
|
+
)
|
879
|
+
|
880
|
+
# I think this is redundant given the scaling in prepare_latents
|
881
|
+
# latents = latents * self.scheduler.config.sigma_data
|
882
|
+
|
883
|
+
guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
|
884
|
+
guidance = guidance.expand(latents.shape[0]).to(prompt_embeds.dtype)
|
885
|
+
guidance = guidance * self.transformer.config.guidance_embeds_scale
|
886
|
+
|
887
|
+
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
888
|
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
889
|
+
|
890
|
+
# 7. Denoising loop
|
891
|
+
timesteps = timesteps[:-1]
|
892
|
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
893
|
+
self._num_timesteps = len(timesteps)
|
894
|
+
|
895
|
+
transformer_dtype = self.transformer.dtype
|
896
|
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
897
|
+
for i, t in enumerate(timesteps):
|
898
|
+
if self.interrupt:
|
899
|
+
continue
|
900
|
+
|
901
|
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
902
|
+
timestep = t.expand(latents.shape[0])
|
903
|
+
latents_model_input = latents / self.scheduler.config.sigma_data
|
904
|
+
|
905
|
+
scm_timestep = torch.sin(timestep) / (torch.cos(timestep) + torch.sin(timestep))
|
906
|
+
|
907
|
+
scm_timestep_expanded = scm_timestep.view(-1, 1, 1, 1)
|
908
|
+
latent_model_input = latents_model_input * torch.sqrt(
|
909
|
+
scm_timestep_expanded**2 + (1 - scm_timestep_expanded) ** 2
|
910
|
+
)
|
911
|
+
|
912
|
+
# predict noise model_output
|
913
|
+
noise_pred = self.transformer(
|
914
|
+
latent_model_input.to(dtype=transformer_dtype),
|
915
|
+
encoder_hidden_states=prompt_embeds.to(dtype=transformer_dtype),
|
916
|
+
encoder_attention_mask=prompt_attention_mask,
|
917
|
+
guidance=guidance,
|
918
|
+
timestep=scm_timestep,
|
919
|
+
return_dict=False,
|
920
|
+
attention_kwargs=self.attention_kwargs,
|
921
|
+
)[0]
|
922
|
+
|
923
|
+
noise_pred = (
|
924
|
+
(1 - 2 * scm_timestep_expanded) * latent_model_input
|
925
|
+
+ (1 - 2 * scm_timestep_expanded + 2 * scm_timestep_expanded**2) * noise_pred
|
926
|
+
) / torch.sqrt(scm_timestep_expanded**2 + (1 - scm_timestep_expanded) ** 2)
|
927
|
+
noise_pred = noise_pred.float() * self.scheduler.config.sigma_data
|
928
|
+
|
929
|
+
# compute previous image: x_t -> x_t-1
|
930
|
+
latents, denoised = self.scheduler.step(
|
931
|
+
noise_pred, timestep, latents, **extra_step_kwargs, return_dict=False
|
932
|
+
)
|
933
|
+
|
934
|
+
if callback_on_step_end is not None:
|
935
|
+
callback_kwargs = {}
|
936
|
+
for k in callback_on_step_end_tensor_inputs:
|
937
|
+
callback_kwargs[k] = locals()[k]
|
938
|
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
939
|
+
|
940
|
+
latents = callback_outputs.pop("latents", latents)
|
941
|
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
942
|
+
|
943
|
+
# call the callback, if provided
|
944
|
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
945
|
+
progress_bar.update()
|
946
|
+
|
947
|
+
if XLA_AVAILABLE:
|
948
|
+
xm.mark_step()
|
949
|
+
|
950
|
+
latents = denoised / self.scheduler.config.sigma_data
|
951
|
+
if output_type == "latent":
|
952
|
+
image = latents
|
953
|
+
else:
|
954
|
+
latents = latents.to(self.vae.dtype)
|
955
|
+
torch_accelerator_module = getattr(torch, get_device(), torch.cuda)
|
956
|
+
oom_error = (
|
957
|
+
torch.OutOfMemoryError
|
958
|
+
if is_torch_version(">=", "2.5.0")
|
959
|
+
else torch_accelerator_module.OutOfMemoryError
|
960
|
+
)
|
961
|
+
try:
|
962
|
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
963
|
+
except oom_error as e:
|
964
|
+
warnings.warn(
|
965
|
+
f"{e}. \n"
|
966
|
+
f"Try to use VAE tiling for large images. For example: \n"
|
967
|
+
f"pipe.vae.enable_tiling(tile_sample_min_width=512, tile_sample_min_height=512)"
|
968
|
+
)
|
969
|
+
if use_resolution_binning:
|
970
|
+
image = self.image_processor.resize_and_crop_tensor(image, orig_width, orig_height)
|
971
|
+
|
972
|
+
if not output_type == "latent":
|
973
|
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
974
|
+
|
975
|
+
# Offload all models
|
976
|
+
self.maybe_free_model_hooks()
|
977
|
+
|
978
|
+
if not return_dict:
|
979
|
+
return (image,)
|
980
|
+
|
981
|
+
return SanaPipelineOutput(images=image)
|