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,772 @@
|
|
1
|
+
# Copyright 2024 The CogVideoX team, Tsinghua University & ZhipuAI and The HuggingFace Team.
|
2
|
+
# All rights reserved.
|
3
|
+
#
|
4
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5
|
+
# you may not use this file except in compliance with the License.
|
6
|
+
# You may obtain a copy of the License at
|
7
|
+
#
|
8
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9
|
+
#
|
10
|
+
# Unless required by applicable law or agreed to in writing, software
|
11
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13
|
+
# See the License for the specific language governing permissions and
|
14
|
+
# limitations under the License.
|
15
|
+
|
16
|
+
import inspect
|
17
|
+
import math
|
18
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
19
|
+
|
20
|
+
import torch
|
21
|
+
from transformers import T5EncoderModel, T5Tokenizer
|
22
|
+
|
23
|
+
from ...callbacks import MultiPipelineCallbacks, PipelineCallback
|
24
|
+
from ...loaders import CogVideoXLoraLoaderMixin
|
25
|
+
from ...models import AutoencoderKLCogVideoX, CogVideoXTransformer3DModel
|
26
|
+
from ...models.embeddings import get_3d_rotary_pos_embed
|
27
|
+
from ...pipelines.pipeline_utils import DiffusionPipeline
|
28
|
+
from ...schedulers import CogVideoXDDIMScheduler, CogVideoXDPMScheduler
|
29
|
+
from ...utils import logging, replace_example_docstring
|
30
|
+
from ...utils.torch_utils import randn_tensor
|
31
|
+
from ...video_processor import VideoProcessor
|
32
|
+
from .pipeline_output import CogVideoXPipelineOutput
|
33
|
+
|
34
|
+
|
35
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
36
|
+
|
37
|
+
|
38
|
+
EXAMPLE_DOC_STRING = """
|
39
|
+
Examples:
|
40
|
+
```python
|
41
|
+
>>> import torch
|
42
|
+
>>> from diffusers import CogVideoXPipeline
|
43
|
+
>>> from diffusers.utils import export_to_video
|
44
|
+
|
45
|
+
>>> # Models: "THUDM/CogVideoX-2b" or "THUDM/CogVideoX-5b"
|
46
|
+
>>> pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-2b", torch_dtype=torch.float16).to("cuda")
|
47
|
+
>>> prompt = (
|
48
|
+
... "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. "
|
49
|
+
... "The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other "
|
50
|
+
... "pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, "
|
51
|
+
... "casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. "
|
52
|
+
... "The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical "
|
53
|
+
... "atmosphere of this unique musical performance."
|
54
|
+
... )
|
55
|
+
>>> video = pipe(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0]
|
56
|
+
>>> export_to_video(video, "output.mp4", fps=8)
|
57
|
+
```
|
58
|
+
"""
|
59
|
+
|
60
|
+
|
61
|
+
# Similar to diffusers.pipelines.hunyuandit.pipeline_hunyuandit.get_resize_crop_region_for_grid
|
62
|
+
def get_resize_crop_region_for_grid(src, tgt_width, tgt_height):
|
63
|
+
tw = tgt_width
|
64
|
+
th = tgt_height
|
65
|
+
h, w = src
|
66
|
+
r = h / w
|
67
|
+
if r > (th / tw):
|
68
|
+
resize_height = th
|
69
|
+
resize_width = int(round(th / h * w))
|
70
|
+
else:
|
71
|
+
resize_width = tw
|
72
|
+
resize_height = int(round(tw / w * h))
|
73
|
+
|
74
|
+
crop_top = int(round((th - resize_height) / 2.0))
|
75
|
+
crop_left = int(round((tw - resize_width) / 2.0))
|
76
|
+
|
77
|
+
return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)
|
78
|
+
|
79
|
+
|
80
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
81
|
+
def retrieve_timesteps(
|
82
|
+
scheduler,
|
83
|
+
num_inference_steps: Optional[int] = None,
|
84
|
+
device: Optional[Union[str, torch.device]] = None,
|
85
|
+
timesteps: Optional[List[int]] = None,
|
86
|
+
sigmas: Optional[List[float]] = None,
|
87
|
+
**kwargs,
|
88
|
+
):
|
89
|
+
r"""
|
90
|
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
91
|
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
92
|
+
|
93
|
+
Args:
|
94
|
+
scheduler (`SchedulerMixin`):
|
95
|
+
The scheduler to get timesteps from.
|
96
|
+
num_inference_steps (`int`):
|
97
|
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
98
|
+
must be `None`.
|
99
|
+
device (`str` or `torch.device`, *optional*):
|
100
|
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
101
|
+
timesteps (`List[int]`, *optional*):
|
102
|
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
103
|
+
`num_inference_steps` and `sigmas` must be `None`.
|
104
|
+
sigmas (`List[float]`, *optional*):
|
105
|
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
106
|
+
`num_inference_steps` and `timesteps` must be `None`.
|
107
|
+
|
108
|
+
Returns:
|
109
|
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
110
|
+
second element is the number of inference steps.
|
111
|
+
"""
|
112
|
+
if timesteps is not None and sigmas is not None:
|
113
|
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
114
|
+
if timesteps is not None:
|
115
|
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
116
|
+
if not accepts_timesteps:
|
117
|
+
raise ValueError(
|
118
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
119
|
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
120
|
+
)
|
121
|
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
122
|
+
timesteps = scheduler.timesteps
|
123
|
+
num_inference_steps = len(timesteps)
|
124
|
+
elif sigmas is not None:
|
125
|
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
126
|
+
if not accept_sigmas:
|
127
|
+
raise ValueError(
|
128
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
129
|
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
130
|
+
)
|
131
|
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
132
|
+
timesteps = scheduler.timesteps
|
133
|
+
num_inference_steps = len(timesteps)
|
134
|
+
else:
|
135
|
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
136
|
+
timesteps = scheduler.timesteps
|
137
|
+
return timesteps, num_inference_steps
|
138
|
+
|
139
|
+
|
140
|
+
class CogVideoXPipeline(DiffusionPipeline, CogVideoXLoraLoaderMixin):
|
141
|
+
r"""
|
142
|
+
Pipeline for text-to-video generation using CogVideoX.
|
143
|
+
|
144
|
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
145
|
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
146
|
+
|
147
|
+
Args:
|
148
|
+
vae ([`AutoencoderKL`]):
|
149
|
+
Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
|
150
|
+
text_encoder ([`T5EncoderModel`]):
|
151
|
+
Frozen text-encoder. CogVideoX uses
|
152
|
+
[T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel); specifically the
|
153
|
+
[t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant.
|
154
|
+
tokenizer (`T5Tokenizer`):
|
155
|
+
Tokenizer of class
|
156
|
+
[T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
|
157
|
+
transformer ([`CogVideoXTransformer3DModel`]):
|
158
|
+
A text conditioned `CogVideoXTransformer3DModel` to denoise the encoded video latents.
|
159
|
+
scheduler ([`SchedulerMixin`]):
|
160
|
+
A scheduler to be used in combination with `transformer` to denoise the encoded video latents.
|
161
|
+
"""
|
162
|
+
|
163
|
+
_optional_components = []
|
164
|
+
model_cpu_offload_seq = "text_encoder->transformer->vae"
|
165
|
+
|
166
|
+
_callback_tensor_inputs = [
|
167
|
+
"latents",
|
168
|
+
"prompt_embeds",
|
169
|
+
"negative_prompt_embeds",
|
170
|
+
]
|
171
|
+
|
172
|
+
def __init__(
|
173
|
+
self,
|
174
|
+
tokenizer: T5Tokenizer,
|
175
|
+
text_encoder: T5EncoderModel,
|
176
|
+
vae: AutoencoderKLCogVideoX,
|
177
|
+
transformer: CogVideoXTransformer3DModel,
|
178
|
+
scheduler: Union[CogVideoXDDIMScheduler, CogVideoXDPMScheduler],
|
179
|
+
):
|
180
|
+
super().__init__()
|
181
|
+
|
182
|
+
self.register_modules(
|
183
|
+
tokenizer=tokenizer, text_encoder=text_encoder, vae=vae, transformer=transformer, scheduler=scheduler
|
184
|
+
)
|
185
|
+
self.vae_scale_factor_spatial = (
|
186
|
+
2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
|
187
|
+
)
|
188
|
+
self.vae_scale_factor_temporal = (
|
189
|
+
self.vae.config.temporal_compression_ratio if hasattr(self, "vae") and self.vae is not None else 4
|
190
|
+
)
|
191
|
+
self.vae_scaling_factor_image = (
|
192
|
+
self.vae.config.scaling_factor if hasattr(self, "vae") and self.vae is not None else 0.7
|
193
|
+
)
|
194
|
+
|
195
|
+
self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
|
196
|
+
|
197
|
+
def _get_t5_prompt_embeds(
|
198
|
+
self,
|
199
|
+
prompt: Union[str, List[str]] = None,
|
200
|
+
num_videos_per_prompt: int = 1,
|
201
|
+
max_sequence_length: int = 226,
|
202
|
+
device: Optional[torch.device] = None,
|
203
|
+
dtype: Optional[torch.dtype] = None,
|
204
|
+
):
|
205
|
+
device = device or self._execution_device
|
206
|
+
dtype = dtype or self.text_encoder.dtype
|
207
|
+
|
208
|
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
209
|
+
batch_size = len(prompt)
|
210
|
+
|
211
|
+
text_inputs = self.tokenizer(
|
212
|
+
prompt,
|
213
|
+
padding="max_length",
|
214
|
+
max_length=max_sequence_length,
|
215
|
+
truncation=True,
|
216
|
+
add_special_tokens=True,
|
217
|
+
return_tensors="pt",
|
218
|
+
)
|
219
|
+
text_input_ids = text_inputs.input_ids
|
220
|
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
221
|
+
|
222
|
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
223
|
+
removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
|
224
|
+
logger.warning(
|
225
|
+
"The following part of your input was truncated because `max_sequence_length` is set to "
|
226
|
+
f" {max_sequence_length} tokens: {removed_text}"
|
227
|
+
)
|
228
|
+
|
229
|
+
prompt_embeds = self.text_encoder(text_input_ids.to(device))[0]
|
230
|
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
231
|
+
|
232
|
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
233
|
+
_, seq_len, _ = prompt_embeds.shape
|
234
|
+
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
|
235
|
+
prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
|
236
|
+
|
237
|
+
return prompt_embeds
|
238
|
+
|
239
|
+
def encode_prompt(
|
240
|
+
self,
|
241
|
+
prompt: Union[str, List[str]],
|
242
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
243
|
+
do_classifier_free_guidance: bool = True,
|
244
|
+
num_videos_per_prompt: int = 1,
|
245
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
246
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
247
|
+
max_sequence_length: int = 226,
|
248
|
+
device: Optional[torch.device] = None,
|
249
|
+
dtype: Optional[torch.dtype] = None,
|
250
|
+
):
|
251
|
+
r"""
|
252
|
+
Encodes the prompt into text encoder hidden states.
|
253
|
+
|
254
|
+
Args:
|
255
|
+
prompt (`str` or `List[str]`, *optional*):
|
256
|
+
prompt to be encoded
|
257
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
258
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
259
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
260
|
+
less than `1`).
|
261
|
+
do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
|
262
|
+
Whether to use classifier free guidance or not.
|
263
|
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
264
|
+
Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
|
265
|
+
prompt_embeds (`torch.Tensor`, *optional*):
|
266
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
267
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
268
|
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
269
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
270
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
271
|
+
argument.
|
272
|
+
device: (`torch.device`, *optional*):
|
273
|
+
torch device
|
274
|
+
dtype: (`torch.dtype`, *optional*):
|
275
|
+
torch dtype
|
276
|
+
"""
|
277
|
+
device = device or self._execution_device
|
278
|
+
|
279
|
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
280
|
+
if prompt is not None:
|
281
|
+
batch_size = len(prompt)
|
282
|
+
else:
|
283
|
+
batch_size = prompt_embeds.shape[0]
|
284
|
+
|
285
|
+
if prompt_embeds is None:
|
286
|
+
prompt_embeds = self._get_t5_prompt_embeds(
|
287
|
+
prompt=prompt,
|
288
|
+
num_videos_per_prompt=num_videos_per_prompt,
|
289
|
+
max_sequence_length=max_sequence_length,
|
290
|
+
device=device,
|
291
|
+
dtype=dtype,
|
292
|
+
)
|
293
|
+
|
294
|
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
295
|
+
negative_prompt = negative_prompt or ""
|
296
|
+
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
297
|
+
|
298
|
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
299
|
+
raise TypeError(
|
300
|
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
301
|
+
f" {type(prompt)}."
|
302
|
+
)
|
303
|
+
elif batch_size != len(negative_prompt):
|
304
|
+
raise ValueError(
|
305
|
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
306
|
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
307
|
+
" the batch size of `prompt`."
|
308
|
+
)
|
309
|
+
|
310
|
+
negative_prompt_embeds = self._get_t5_prompt_embeds(
|
311
|
+
prompt=negative_prompt,
|
312
|
+
num_videos_per_prompt=num_videos_per_prompt,
|
313
|
+
max_sequence_length=max_sequence_length,
|
314
|
+
device=device,
|
315
|
+
dtype=dtype,
|
316
|
+
)
|
317
|
+
|
318
|
+
return prompt_embeds, negative_prompt_embeds
|
319
|
+
|
320
|
+
def prepare_latents(
|
321
|
+
self, batch_size, num_channels_latents, num_frames, height, width, dtype, device, generator, latents=None
|
322
|
+
):
|
323
|
+
if isinstance(generator, list) and len(generator) != batch_size:
|
324
|
+
raise ValueError(
|
325
|
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
326
|
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
327
|
+
)
|
328
|
+
|
329
|
+
shape = (
|
330
|
+
batch_size,
|
331
|
+
(num_frames - 1) // self.vae_scale_factor_temporal + 1,
|
332
|
+
num_channels_latents,
|
333
|
+
height // self.vae_scale_factor_spatial,
|
334
|
+
width // self.vae_scale_factor_spatial,
|
335
|
+
)
|
336
|
+
|
337
|
+
if latents is None:
|
338
|
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
339
|
+
else:
|
340
|
+
latents = latents.to(device)
|
341
|
+
|
342
|
+
# scale the initial noise by the standard deviation required by the scheduler
|
343
|
+
latents = latents * self.scheduler.init_noise_sigma
|
344
|
+
return latents
|
345
|
+
|
346
|
+
def decode_latents(self, latents: torch.Tensor) -> torch.Tensor:
|
347
|
+
latents = latents.permute(0, 2, 1, 3, 4) # [batch_size, num_channels, num_frames, height, width]
|
348
|
+
latents = 1 / self.vae_scaling_factor_image * latents
|
349
|
+
|
350
|
+
frames = self.vae.decode(latents).sample
|
351
|
+
return frames
|
352
|
+
|
353
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
354
|
+
def prepare_extra_step_kwargs(self, generator, eta):
|
355
|
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
356
|
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
357
|
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
358
|
+
# and should be between [0, 1]
|
359
|
+
|
360
|
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
361
|
+
extra_step_kwargs = {}
|
362
|
+
if accepts_eta:
|
363
|
+
extra_step_kwargs["eta"] = eta
|
364
|
+
|
365
|
+
# check if the scheduler accepts generator
|
366
|
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
367
|
+
if accepts_generator:
|
368
|
+
extra_step_kwargs["generator"] = generator
|
369
|
+
return extra_step_kwargs
|
370
|
+
|
371
|
+
# Copied from diffusers.pipelines.latte.pipeline_latte.LattePipeline.check_inputs
|
372
|
+
def check_inputs(
|
373
|
+
self,
|
374
|
+
prompt,
|
375
|
+
height,
|
376
|
+
width,
|
377
|
+
negative_prompt,
|
378
|
+
callback_on_step_end_tensor_inputs,
|
379
|
+
prompt_embeds=None,
|
380
|
+
negative_prompt_embeds=None,
|
381
|
+
):
|
382
|
+
if height % 8 != 0 or width % 8 != 0:
|
383
|
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
384
|
+
|
385
|
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
386
|
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
387
|
+
):
|
388
|
+
raise ValueError(
|
389
|
+
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]}"
|
390
|
+
)
|
391
|
+
if prompt is not None and prompt_embeds is not None:
|
392
|
+
raise ValueError(
|
393
|
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
394
|
+
" only forward one of the two."
|
395
|
+
)
|
396
|
+
elif prompt is None and prompt_embeds is None:
|
397
|
+
raise ValueError(
|
398
|
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
399
|
+
)
|
400
|
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
401
|
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
402
|
+
|
403
|
+
if prompt is not None and negative_prompt_embeds is not None:
|
404
|
+
raise ValueError(
|
405
|
+
f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:"
|
406
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
407
|
+
)
|
408
|
+
|
409
|
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
410
|
+
raise ValueError(
|
411
|
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
412
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
413
|
+
)
|
414
|
+
|
415
|
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
416
|
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
417
|
+
raise ValueError(
|
418
|
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
419
|
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
420
|
+
f" {negative_prompt_embeds.shape}."
|
421
|
+
)
|
422
|
+
|
423
|
+
def fuse_qkv_projections(self) -> None:
|
424
|
+
r"""Enables fused QKV projections."""
|
425
|
+
self.fusing_transformer = True
|
426
|
+
self.transformer.fuse_qkv_projections()
|
427
|
+
|
428
|
+
def unfuse_qkv_projections(self) -> None:
|
429
|
+
r"""Disable QKV projection fusion if enabled."""
|
430
|
+
if not self.fusing_transformer:
|
431
|
+
logger.warning("The Transformer was not initially fused for QKV projections. Doing nothing.")
|
432
|
+
else:
|
433
|
+
self.transformer.unfuse_qkv_projections()
|
434
|
+
self.fusing_transformer = False
|
435
|
+
|
436
|
+
def _prepare_rotary_positional_embeddings(
|
437
|
+
self,
|
438
|
+
height: int,
|
439
|
+
width: int,
|
440
|
+
num_frames: int,
|
441
|
+
device: torch.device,
|
442
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
443
|
+
grid_height = height // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
|
444
|
+
grid_width = width // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
|
445
|
+
|
446
|
+
p = self.transformer.config.patch_size
|
447
|
+
p_t = self.transformer.config.patch_size_t
|
448
|
+
|
449
|
+
base_size_width = self.transformer.config.sample_width // p
|
450
|
+
base_size_height = self.transformer.config.sample_height // p
|
451
|
+
|
452
|
+
if p_t is None:
|
453
|
+
# CogVideoX 1.0
|
454
|
+
grid_crops_coords = get_resize_crop_region_for_grid(
|
455
|
+
(grid_height, grid_width), base_size_width, base_size_height
|
456
|
+
)
|
457
|
+
freqs_cos, freqs_sin = get_3d_rotary_pos_embed(
|
458
|
+
embed_dim=self.transformer.config.attention_head_dim,
|
459
|
+
crops_coords=grid_crops_coords,
|
460
|
+
grid_size=(grid_height, grid_width),
|
461
|
+
temporal_size=num_frames,
|
462
|
+
device=device,
|
463
|
+
)
|
464
|
+
else:
|
465
|
+
# CogVideoX 1.5
|
466
|
+
base_num_frames = (num_frames + p_t - 1) // p_t
|
467
|
+
|
468
|
+
freqs_cos, freqs_sin = get_3d_rotary_pos_embed(
|
469
|
+
embed_dim=self.transformer.config.attention_head_dim,
|
470
|
+
crops_coords=None,
|
471
|
+
grid_size=(grid_height, grid_width),
|
472
|
+
temporal_size=base_num_frames,
|
473
|
+
grid_type="slice",
|
474
|
+
max_size=(base_size_height, base_size_width),
|
475
|
+
device=device,
|
476
|
+
)
|
477
|
+
|
478
|
+
return freqs_cos, freqs_sin
|
479
|
+
|
480
|
+
@property
|
481
|
+
def guidance_scale(self):
|
482
|
+
return self._guidance_scale
|
483
|
+
|
484
|
+
@property
|
485
|
+
def num_timesteps(self):
|
486
|
+
return self._num_timesteps
|
487
|
+
|
488
|
+
@property
|
489
|
+
def attention_kwargs(self):
|
490
|
+
return self._attention_kwargs
|
491
|
+
|
492
|
+
@property
|
493
|
+
def interrupt(self):
|
494
|
+
return self._interrupt
|
495
|
+
|
496
|
+
@torch.no_grad()
|
497
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
498
|
+
def __call__(
|
499
|
+
self,
|
500
|
+
prompt: Optional[Union[str, List[str]]] = None,
|
501
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
502
|
+
height: Optional[int] = None,
|
503
|
+
width: Optional[int] = None,
|
504
|
+
num_frames: Optional[int] = None,
|
505
|
+
num_inference_steps: int = 50,
|
506
|
+
timesteps: Optional[List[int]] = None,
|
507
|
+
guidance_scale: float = 6,
|
508
|
+
use_dynamic_cfg: bool = False,
|
509
|
+
num_videos_per_prompt: int = 1,
|
510
|
+
eta: float = 0.0,
|
511
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
512
|
+
latents: Optional[torch.FloatTensor] = None,
|
513
|
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
514
|
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
515
|
+
output_type: str = "pil",
|
516
|
+
return_dict: bool = True,
|
517
|
+
attention_kwargs: Optional[Dict[str, Any]] = None,
|
518
|
+
callback_on_step_end: Optional[
|
519
|
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
520
|
+
] = None,
|
521
|
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
522
|
+
max_sequence_length: int = 226,
|
523
|
+
) -> Union[CogVideoXPipelineOutput, Tuple]:
|
524
|
+
"""
|
525
|
+
Function invoked when calling the pipeline for generation.
|
526
|
+
|
527
|
+
Args:
|
528
|
+
prompt (`str` or `List[str]`, *optional*):
|
529
|
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
530
|
+
instead.
|
531
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
532
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
533
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
534
|
+
less than `1`).
|
535
|
+
height (`int`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial):
|
536
|
+
The height in pixels of the generated image. This is set to 480 by default for the best results.
|
537
|
+
width (`int`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial):
|
538
|
+
The width in pixels of the generated image. This is set to 720 by default for the best results.
|
539
|
+
num_frames (`int`, defaults to `48`):
|
540
|
+
Number of frames to generate. Must be divisible by self.vae_scale_factor_temporal. Generated video will
|
541
|
+
contain 1 extra frame because CogVideoX is conditioned with (num_seconds * fps + 1) frames where
|
542
|
+
num_seconds is 6 and fps is 8. However, since videos can be saved at any fps, the only condition that
|
543
|
+
needs to be satisfied is that of divisibility mentioned above.
|
544
|
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
545
|
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
546
|
+
expense of slower inference.
|
547
|
+
timesteps (`List[int]`, *optional*):
|
548
|
+
Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
|
549
|
+
in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
|
550
|
+
passed will be used. Must be in descending order.
|
551
|
+
guidance_scale (`float`, *optional*, defaults to 7.0):
|
552
|
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
553
|
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
554
|
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
555
|
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
556
|
+
usually at the expense of lower image quality.
|
557
|
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
558
|
+
The number of videos to generate per prompt.
|
559
|
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
560
|
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
561
|
+
to make generation deterministic.
|
562
|
+
latents (`torch.FloatTensor`, *optional*):
|
563
|
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
564
|
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
565
|
+
tensor will ge generated by sampling using the supplied random `generator`.
|
566
|
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
567
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
568
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
569
|
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
570
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
571
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
572
|
+
argument.
|
573
|
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
574
|
+
The output format of the generate image. Choose between
|
575
|
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
576
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
577
|
+
Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
|
578
|
+
of a plain tuple.
|
579
|
+
attention_kwargs (`dict`, *optional*):
|
580
|
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
581
|
+
`self.processor` in
|
582
|
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
583
|
+
callback_on_step_end (`Callable`, *optional*):
|
584
|
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
585
|
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
586
|
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
587
|
+
`callback_on_step_end_tensor_inputs`.
|
588
|
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
589
|
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
590
|
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
591
|
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
592
|
+
max_sequence_length (`int`, defaults to `226`):
|
593
|
+
Maximum sequence length in encoded prompt. Must be consistent with
|
594
|
+
`self.transformer.config.max_text_seq_length` otherwise may lead to poor results.
|
595
|
+
|
596
|
+
Examples:
|
597
|
+
|
598
|
+
Returns:
|
599
|
+
[`~pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipelineOutput`] or `tuple`:
|
600
|
+
[`~pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipelineOutput`] if `return_dict` is True, otherwise a
|
601
|
+
`tuple`. When returning a tuple, the first element is a list with the generated images.
|
602
|
+
"""
|
603
|
+
|
604
|
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
605
|
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
606
|
+
|
607
|
+
height = height or self.transformer.config.sample_height * self.vae_scale_factor_spatial
|
608
|
+
width = width or self.transformer.config.sample_width * self.vae_scale_factor_spatial
|
609
|
+
num_frames = num_frames or self.transformer.config.sample_frames
|
610
|
+
|
611
|
+
num_videos_per_prompt = 1
|
612
|
+
|
613
|
+
# 1. Check inputs. Raise error if not correct
|
614
|
+
self.check_inputs(
|
615
|
+
prompt,
|
616
|
+
height,
|
617
|
+
width,
|
618
|
+
negative_prompt,
|
619
|
+
callback_on_step_end_tensor_inputs,
|
620
|
+
prompt_embeds,
|
621
|
+
negative_prompt_embeds,
|
622
|
+
)
|
623
|
+
self._guidance_scale = guidance_scale
|
624
|
+
self._attention_kwargs = attention_kwargs
|
625
|
+
self._interrupt = False
|
626
|
+
|
627
|
+
# 2. Default call parameters
|
628
|
+
if prompt is not None and isinstance(prompt, str):
|
629
|
+
batch_size = 1
|
630
|
+
elif prompt is not None and isinstance(prompt, list):
|
631
|
+
batch_size = len(prompt)
|
632
|
+
else:
|
633
|
+
batch_size = prompt_embeds.shape[0]
|
634
|
+
|
635
|
+
device = self._execution_device
|
636
|
+
|
637
|
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
638
|
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
639
|
+
# corresponds to doing no classifier free guidance.
|
640
|
+
do_classifier_free_guidance = guidance_scale > 1.0
|
641
|
+
|
642
|
+
# 3. Encode input prompt
|
643
|
+
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
644
|
+
prompt,
|
645
|
+
negative_prompt,
|
646
|
+
do_classifier_free_guidance,
|
647
|
+
num_videos_per_prompt=num_videos_per_prompt,
|
648
|
+
prompt_embeds=prompt_embeds,
|
649
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
650
|
+
max_sequence_length=max_sequence_length,
|
651
|
+
device=device,
|
652
|
+
)
|
653
|
+
if do_classifier_free_guidance:
|
654
|
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
655
|
+
|
656
|
+
# 4. Prepare timesteps
|
657
|
+
timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
|
658
|
+
self._num_timesteps = len(timesteps)
|
659
|
+
|
660
|
+
# 5. Prepare latents
|
661
|
+
latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
|
662
|
+
|
663
|
+
# For CogVideoX 1.5, the latent frames should be padded to make it divisible by patch_size_t
|
664
|
+
patch_size_t = self.transformer.config.patch_size_t
|
665
|
+
additional_frames = 0
|
666
|
+
if patch_size_t is not None and latent_frames % patch_size_t != 0:
|
667
|
+
additional_frames = patch_size_t - latent_frames % patch_size_t
|
668
|
+
num_frames += additional_frames * self.vae_scale_factor_temporal
|
669
|
+
|
670
|
+
latent_channels = self.transformer.config.in_channels
|
671
|
+
latents = self.prepare_latents(
|
672
|
+
batch_size * num_videos_per_prompt,
|
673
|
+
latent_channels,
|
674
|
+
num_frames,
|
675
|
+
height,
|
676
|
+
width,
|
677
|
+
prompt_embeds.dtype,
|
678
|
+
device,
|
679
|
+
generator,
|
680
|
+
latents,
|
681
|
+
)
|
682
|
+
|
683
|
+
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
684
|
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
685
|
+
|
686
|
+
# 7. Create rotary embeds if required
|
687
|
+
image_rotary_emb = (
|
688
|
+
self._prepare_rotary_positional_embeddings(height, width, latents.size(1), device)
|
689
|
+
if self.transformer.config.use_rotary_positional_embeddings
|
690
|
+
else None
|
691
|
+
)
|
692
|
+
|
693
|
+
# 8. Denoising loop
|
694
|
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
695
|
+
|
696
|
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
697
|
+
# for DPM-solver++
|
698
|
+
old_pred_original_sample = None
|
699
|
+
for i, t in enumerate(timesteps):
|
700
|
+
if self.interrupt:
|
701
|
+
continue
|
702
|
+
|
703
|
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
704
|
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
705
|
+
|
706
|
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
707
|
+
timestep = t.expand(latent_model_input.shape[0])
|
708
|
+
|
709
|
+
# predict noise model_output
|
710
|
+
noise_pred = self.transformer(
|
711
|
+
hidden_states=latent_model_input,
|
712
|
+
encoder_hidden_states=prompt_embeds,
|
713
|
+
timestep=timestep,
|
714
|
+
image_rotary_emb=image_rotary_emb,
|
715
|
+
attention_kwargs=attention_kwargs,
|
716
|
+
return_dict=False,
|
717
|
+
)[0]
|
718
|
+
noise_pred = noise_pred.float()
|
719
|
+
|
720
|
+
# perform guidance
|
721
|
+
if use_dynamic_cfg:
|
722
|
+
self._guidance_scale = 1 + guidance_scale * (
|
723
|
+
(1 - math.cos(math.pi * ((num_inference_steps - t.item()) / num_inference_steps) ** 5.0)) / 2
|
724
|
+
)
|
725
|
+
if do_classifier_free_guidance:
|
726
|
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
727
|
+
noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
|
728
|
+
|
729
|
+
# compute the previous noisy sample x_t -> x_t-1
|
730
|
+
if not isinstance(self.scheduler, CogVideoXDPMScheduler):
|
731
|
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
732
|
+
else:
|
733
|
+
latents, old_pred_original_sample = self.scheduler.step(
|
734
|
+
noise_pred,
|
735
|
+
old_pred_original_sample,
|
736
|
+
t,
|
737
|
+
timesteps[i - 1] if i > 0 else None,
|
738
|
+
latents,
|
739
|
+
**extra_step_kwargs,
|
740
|
+
return_dict=False,
|
741
|
+
)
|
742
|
+
latents = latents.to(prompt_embeds.dtype)
|
743
|
+
|
744
|
+
# call the callback, if provided
|
745
|
+
if callback_on_step_end is not None:
|
746
|
+
callback_kwargs = {}
|
747
|
+
for k in callback_on_step_end_tensor_inputs:
|
748
|
+
callback_kwargs[k] = locals()[k]
|
749
|
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
750
|
+
|
751
|
+
latents = callback_outputs.pop("latents", latents)
|
752
|
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
753
|
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
754
|
+
|
755
|
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
756
|
+
progress_bar.update()
|
757
|
+
|
758
|
+
if not output_type == "latent":
|
759
|
+
# Discard any padding frames that were added for CogVideoX 1.5
|
760
|
+
latents = latents[:, additional_frames:]
|
761
|
+
video = self.decode_latents(latents)
|
762
|
+
video = self.video_processor.postprocess_video(video=video, output_type=output_type)
|
763
|
+
else:
|
764
|
+
video = latents
|
765
|
+
|
766
|
+
# Offload all models
|
767
|
+
self.maybe_free_model_hooks()
|
768
|
+
|
769
|
+
if not return_dict:
|
770
|
+
return (video,)
|
771
|
+
|
772
|
+
return CogVideoXPipelineOutput(frames=video)
|