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,1482 @@
|
|
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
|
+
from typing import Dict, Optional, Tuple, Union
|
17
|
+
|
18
|
+
import numpy as np
|
19
|
+
import torch
|
20
|
+
import torch.nn as nn
|
21
|
+
import torch.nn.functional as F
|
22
|
+
|
23
|
+
from ...configuration_utils import ConfigMixin, register_to_config
|
24
|
+
from ...loaders.single_file_model import FromOriginalModelMixin
|
25
|
+
from ...utils import logging
|
26
|
+
from ...utils.accelerate_utils import apply_forward_hook
|
27
|
+
from ..activations import get_activation
|
28
|
+
from ..downsampling import CogVideoXDownsample3D
|
29
|
+
from ..modeling_outputs import AutoencoderKLOutput
|
30
|
+
from ..modeling_utils import ModelMixin
|
31
|
+
from ..upsampling import CogVideoXUpsample3D
|
32
|
+
from .vae import DecoderOutput, DiagonalGaussianDistribution
|
33
|
+
|
34
|
+
|
35
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
36
|
+
|
37
|
+
|
38
|
+
class CogVideoXSafeConv3d(nn.Conv3d):
|
39
|
+
r"""
|
40
|
+
A 3D convolution layer that splits the input tensor into smaller parts to avoid OOM in CogVideoX Model.
|
41
|
+
"""
|
42
|
+
|
43
|
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
|
44
|
+
memory_count = (
|
45
|
+
(input.shape[0] * input.shape[1] * input.shape[2] * input.shape[3] * input.shape[4]) * 2 / 1024**3
|
46
|
+
)
|
47
|
+
|
48
|
+
# Set to 2GB, suitable for CuDNN
|
49
|
+
if memory_count > 2:
|
50
|
+
kernel_size = self.kernel_size[0]
|
51
|
+
part_num = int(memory_count / 2) + 1
|
52
|
+
input_chunks = torch.chunk(input, part_num, dim=2)
|
53
|
+
|
54
|
+
if kernel_size > 1:
|
55
|
+
input_chunks = [input_chunks[0]] + [
|
56
|
+
torch.cat((input_chunks[i - 1][:, :, -kernel_size + 1 :], input_chunks[i]), dim=2)
|
57
|
+
for i in range(1, len(input_chunks))
|
58
|
+
]
|
59
|
+
|
60
|
+
output_chunks = []
|
61
|
+
for input_chunk in input_chunks:
|
62
|
+
output_chunks.append(super().forward(input_chunk))
|
63
|
+
output = torch.cat(output_chunks, dim=2)
|
64
|
+
return output
|
65
|
+
else:
|
66
|
+
return super().forward(input)
|
67
|
+
|
68
|
+
|
69
|
+
class CogVideoXCausalConv3d(nn.Module):
|
70
|
+
r"""A 3D causal convolution layer that pads the input tensor to ensure causality in CogVideoX Model.
|
71
|
+
|
72
|
+
Args:
|
73
|
+
in_channels (`int`): Number of channels in the input tensor.
|
74
|
+
out_channels (`int`): Number of output channels produced by the convolution.
|
75
|
+
kernel_size (`int` or `Tuple[int, int, int]`): Kernel size of the convolutional kernel.
|
76
|
+
stride (`int`, defaults to `1`): Stride of the convolution.
|
77
|
+
dilation (`int`, defaults to `1`): Dilation rate of the convolution.
|
78
|
+
pad_mode (`str`, defaults to `"constant"`): Padding mode.
|
79
|
+
"""
|
80
|
+
|
81
|
+
def __init__(
|
82
|
+
self,
|
83
|
+
in_channels: int,
|
84
|
+
out_channels: int,
|
85
|
+
kernel_size: Union[int, Tuple[int, int, int]],
|
86
|
+
stride: int = 1,
|
87
|
+
dilation: int = 1,
|
88
|
+
pad_mode: str = "constant",
|
89
|
+
):
|
90
|
+
super().__init__()
|
91
|
+
|
92
|
+
if isinstance(kernel_size, int):
|
93
|
+
kernel_size = (kernel_size,) * 3
|
94
|
+
|
95
|
+
time_kernel_size, height_kernel_size, width_kernel_size = kernel_size
|
96
|
+
|
97
|
+
# TODO(aryan): configure calculation based on stride and dilation in the future.
|
98
|
+
# Since CogVideoX does not use it, it is currently tailored to "just work" with Mochi
|
99
|
+
time_pad = time_kernel_size - 1
|
100
|
+
height_pad = (height_kernel_size - 1) // 2
|
101
|
+
width_pad = (width_kernel_size - 1) // 2
|
102
|
+
|
103
|
+
self.pad_mode = pad_mode
|
104
|
+
self.height_pad = height_pad
|
105
|
+
self.width_pad = width_pad
|
106
|
+
self.time_pad = time_pad
|
107
|
+
self.time_causal_padding = (width_pad, width_pad, height_pad, height_pad, time_pad, 0)
|
108
|
+
|
109
|
+
self.temporal_dim = 2
|
110
|
+
self.time_kernel_size = time_kernel_size
|
111
|
+
|
112
|
+
stride = stride if isinstance(stride, tuple) else (stride, 1, 1)
|
113
|
+
dilation = (dilation, 1, 1)
|
114
|
+
self.conv = CogVideoXSafeConv3d(
|
115
|
+
in_channels=in_channels,
|
116
|
+
out_channels=out_channels,
|
117
|
+
kernel_size=kernel_size,
|
118
|
+
stride=stride,
|
119
|
+
dilation=dilation,
|
120
|
+
)
|
121
|
+
|
122
|
+
def fake_context_parallel_forward(
|
123
|
+
self, inputs: torch.Tensor, conv_cache: Optional[torch.Tensor] = None
|
124
|
+
) -> torch.Tensor:
|
125
|
+
if self.pad_mode == "replicate":
|
126
|
+
inputs = F.pad(inputs, self.time_causal_padding, mode="replicate")
|
127
|
+
else:
|
128
|
+
kernel_size = self.time_kernel_size
|
129
|
+
if kernel_size > 1:
|
130
|
+
cached_inputs = [conv_cache] if conv_cache is not None else [inputs[:, :, :1]] * (kernel_size - 1)
|
131
|
+
inputs = torch.cat(cached_inputs + [inputs], dim=2)
|
132
|
+
return inputs
|
133
|
+
|
134
|
+
def forward(self, inputs: torch.Tensor, conv_cache: Optional[torch.Tensor] = None) -> torch.Tensor:
|
135
|
+
inputs = self.fake_context_parallel_forward(inputs, conv_cache)
|
136
|
+
|
137
|
+
if self.pad_mode == "replicate":
|
138
|
+
conv_cache = None
|
139
|
+
else:
|
140
|
+
padding_2d = (self.width_pad, self.width_pad, self.height_pad, self.height_pad)
|
141
|
+
conv_cache = inputs[:, :, -self.time_kernel_size + 1 :].clone()
|
142
|
+
inputs = F.pad(inputs, padding_2d, mode="constant", value=0)
|
143
|
+
|
144
|
+
output = self.conv(inputs)
|
145
|
+
return output, conv_cache
|
146
|
+
|
147
|
+
|
148
|
+
class CogVideoXSpatialNorm3D(nn.Module):
|
149
|
+
r"""
|
150
|
+
Spatially conditioned normalization as defined in https://arxiv.org/abs/2209.09002. This implementation is specific
|
151
|
+
to 3D-video like data.
|
152
|
+
|
153
|
+
CogVideoXSafeConv3d is used instead of nn.Conv3d to avoid OOM in CogVideoX Model.
|
154
|
+
|
155
|
+
Args:
|
156
|
+
f_channels (`int`):
|
157
|
+
The number of channels for input to group normalization layer, and output of the spatial norm layer.
|
158
|
+
zq_channels (`int`):
|
159
|
+
The number of channels for the quantized vector as described in the paper.
|
160
|
+
groups (`int`):
|
161
|
+
Number of groups to separate the channels into for group normalization.
|
162
|
+
"""
|
163
|
+
|
164
|
+
def __init__(
|
165
|
+
self,
|
166
|
+
f_channels: int,
|
167
|
+
zq_channels: int,
|
168
|
+
groups: int = 32,
|
169
|
+
):
|
170
|
+
super().__init__()
|
171
|
+
self.norm_layer = nn.GroupNorm(num_channels=f_channels, num_groups=groups, eps=1e-6, affine=True)
|
172
|
+
self.conv_y = CogVideoXCausalConv3d(zq_channels, f_channels, kernel_size=1, stride=1)
|
173
|
+
self.conv_b = CogVideoXCausalConv3d(zq_channels, f_channels, kernel_size=1, stride=1)
|
174
|
+
|
175
|
+
def forward(
|
176
|
+
self, f: torch.Tensor, zq: torch.Tensor, conv_cache: Optional[Dict[str, torch.Tensor]] = None
|
177
|
+
) -> torch.Tensor:
|
178
|
+
new_conv_cache = {}
|
179
|
+
conv_cache = conv_cache or {}
|
180
|
+
|
181
|
+
if f.shape[2] > 1 and f.shape[2] % 2 == 1:
|
182
|
+
f_first, f_rest = f[:, :, :1], f[:, :, 1:]
|
183
|
+
f_first_size, f_rest_size = f_first.shape[-3:], f_rest.shape[-3:]
|
184
|
+
z_first, z_rest = zq[:, :, :1], zq[:, :, 1:]
|
185
|
+
z_first = F.interpolate(z_first, size=f_first_size)
|
186
|
+
z_rest = F.interpolate(z_rest, size=f_rest_size)
|
187
|
+
zq = torch.cat([z_first, z_rest], dim=2)
|
188
|
+
else:
|
189
|
+
zq = F.interpolate(zq, size=f.shape[-3:])
|
190
|
+
|
191
|
+
conv_y, new_conv_cache["conv_y"] = self.conv_y(zq, conv_cache=conv_cache.get("conv_y"))
|
192
|
+
conv_b, new_conv_cache["conv_b"] = self.conv_b(zq, conv_cache=conv_cache.get("conv_b"))
|
193
|
+
|
194
|
+
norm_f = self.norm_layer(f)
|
195
|
+
new_f = norm_f * conv_y + conv_b
|
196
|
+
return new_f, new_conv_cache
|
197
|
+
|
198
|
+
|
199
|
+
class CogVideoXResnetBlock3D(nn.Module):
|
200
|
+
r"""
|
201
|
+
A 3D ResNet block used in the CogVideoX model.
|
202
|
+
|
203
|
+
Args:
|
204
|
+
in_channels (`int`):
|
205
|
+
Number of input channels.
|
206
|
+
out_channels (`int`, *optional*):
|
207
|
+
Number of output channels. If None, defaults to `in_channels`.
|
208
|
+
dropout (`float`, defaults to `0.0`):
|
209
|
+
Dropout rate.
|
210
|
+
temb_channels (`int`, defaults to `512`):
|
211
|
+
Number of time embedding channels.
|
212
|
+
groups (`int`, defaults to `32`):
|
213
|
+
Number of groups to separate the channels into for group normalization.
|
214
|
+
eps (`float`, defaults to `1e-6`):
|
215
|
+
Epsilon value for normalization layers.
|
216
|
+
non_linearity (`str`, defaults to `"swish"`):
|
217
|
+
Activation function to use.
|
218
|
+
conv_shortcut (bool, defaults to `False`):
|
219
|
+
Whether or not to use a convolution shortcut.
|
220
|
+
spatial_norm_dim (`int`, *optional*):
|
221
|
+
The dimension to use for spatial norm if it is to be used instead of group norm.
|
222
|
+
pad_mode (str, defaults to `"first"`):
|
223
|
+
Padding mode.
|
224
|
+
"""
|
225
|
+
|
226
|
+
def __init__(
|
227
|
+
self,
|
228
|
+
in_channels: int,
|
229
|
+
out_channels: Optional[int] = None,
|
230
|
+
dropout: float = 0.0,
|
231
|
+
temb_channels: int = 512,
|
232
|
+
groups: int = 32,
|
233
|
+
eps: float = 1e-6,
|
234
|
+
non_linearity: str = "swish",
|
235
|
+
conv_shortcut: bool = False,
|
236
|
+
spatial_norm_dim: Optional[int] = None,
|
237
|
+
pad_mode: str = "first",
|
238
|
+
):
|
239
|
+
super().__init__()
|
240
|
+
|
241
|
+
out_channels = out_channels or in_channels
|
242
|
+
|
243
|
+
self.in_channels = in_channels
|
244
|
+
self.out_channels = out_channels
|
245
|
+
self.nonlinearity = get_activation(non_linearity)
|
246
|
+
self.use_conv_shortcut = conv_shortcut
|
247
|
+
self.spatial_norm_dim = spatial_norm_dim
|
248
|
+
|
249
|
+
if spatial_norm_dim is None:
|
250
|
+
self.norm1 = nn.GroupNorm(num_channels=in_channels, num_groups=groups, eps=eps)
|
251
|
+
self.norm2 = nn.GroupNorm(num_channels=out_channels, num_groups=groups, eps=eps)
|
252
|
+
else:
|
253
|
+
self.norm1 = CogVideoXSpatialNorm3D(
|
254
|
+
f_channels=in_channels,
|
255
|
+
zq_channels=spatial_norm_dim,
|
256
|
+
groups=groups,
|
257
|
+
)
|
258
|
+
self.norm2 = CogVideoXSpatialNorm3D(
|
259
|
+
f_channels=out_channels,
|
260
|
+
zq_channels=spatial_norm_dim,
|
261
|
+
groups=groups,
|
262
|
+
)
|
263
|
+
|
264
|
+
self.conv1 = CogVideoXCausalConv3d(
|
265
|
+
in_channels=in_channels, out_channels=out_channels, kernel_size=3, pad_mode=pad_mode
|
266
|
+
)
|
267
|
+
|
268
|
+
if temb_channels > 0:
|
269
|
+
self.temb_proj = nn.Linear(in_features=temb_channels, out_features=out_channels)
|
270
|
+
|
271
|
+
self.dropout = nn.Dropout(dropout)
|
272
|
+
self.conv2 = CogVideoXCausalConv3d(
|
273
|
+
in_channels=out_channels, out_channels=out_channels, kernel_size=3, pad_mode=pad_mode
|
274
|
+
)
|
275
|
+
|
276
|
+
if self.in_channels != self.out_channels:
|
277
|
+
if self.use_conv_shortcut:
|
278
|
+
self.conv_shortcut = CogVideoXCausalConv3d(
|
279
|
+
in_channels=in_channels, out_channels=out_channels, kernel_size=3, pad_mode=pad_mode
|
280
|
+
)
|
281
|
+
else:
|
282
|
+
self.conv_shortcut = CogVideoXSafeConv3d(
|
283
|
+
in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0
|
284
|
+
)
|
285
|
+
|
286
|
+
def forward(
|
287
|
+
self,
|
288
|
+
inputs: torch.Tensor,
|
289
|
+
temb: Optional[torch.Tensor] = None,
|
290
|
+
zq: Optional[torch.Tensor] = None,
|
291
|
+
conv_cache: Optional[Dict[str, torch.Tensor]] = None,
|
292
|
+
) -> torch.Tensor:
|
293
|
+
new_conv_cache = {}
|
294
|
+
conv_cache = conv_cache or {}
|
295
|
+
|
296
|
+
hidden_states = inputs
|
297
|
+
|
298
|
+
if zq is not None:
|
299
|
+
hidden_states, new_conv_cache["norm1"] = self.norm1(hidden_states, zq, conv_cache=conv_cache.get("norm1"))
|
300
|
+
else:
|
301
|
+
hidden_states = self.norm1(hidden_states)
|
302
|
+
|
303
|
+
hidden_states = self.nonlinearity(hidden_states)
|
304
|
+
hidden_states, new_conv_cache["conv1"] = self.conv1(hidden_states, conv_cache=conv_cache.get("conv1"))
|
305
|
+
|
306
|
+
if temb is not None:
|
307
|
+
hidden_states = hidden_states + self.temb_proj(self.nonlinearity(temb))[:, :, None, None, None]
|
308
|
+
|
309
|
+
if zq is not None:
|
310
|
+
hidden_states, new_conv_cache["norm2"] = self.norm2(hidden_states, zq, conv_cache=conv_cache.get("norm2"))
|
311
|
+
else:
|
312
|
+
hidden_states = self.norm2(hidden_states)
|
313
|
+
|
314
|
+
hidden_states = self.nonlinearity(hidden_states)
|
315
|
+
hidden_states = self.dropout(hidden_states)
|
316
|
+
hidden_states, new_conv_cache["conv2"] = self.conv2(hidden_states, conv_cache=conv_cache.get("conv2"))
|
317
|
+
|
318
|
+
if self.in_channels != self.out_channels:
|
319
|
+
if self.use_conv_shortcut:
|
320
|
+
inputs, new_conv_cache["conv_shortcut"] = self.conv_shortcut(
|
321
|
+
inputs, conv_cache=conv_cache.get("conv_shortcut")
|
322
|
+
)
|
323
|
+
else:
|
324
|
+
inputs = self.conv_shortcut(inputs)
|
325
|
+
|
326
|
+
hidden_states = hidden_states + inputs
|
327
|
+
return hidden_states, new_conv_cache
|
328
|
+
|
329
|
+
|
330
|
+
class CogVideoXDownBlock3D(nn.Module):
|
331
|
+
r"""
|
332
|
+
A downsampling block used in the CogVideoX model.
|
333
|
+
|
334
|
+
Args:
|
335
|
+
in_channels (`int`):
|
336
|
+
Number of input channels.
|
337
|
+
out_channels (`int`, *optional*):
|
338
|
+
Number of output channels. If None, defaults to `in_channels`.
|
339
|
+
temb_channels (`int`, defaults to `512`):
|
340
|
+
Number of time embedding channels.
|
341
|
+
num_layers (`int`, defaults to `1`):
|
342
|
+
Number of resnet layers.
|
343
|
+
dropout (`float`, defaults to `0.0`):
|
344
|
+
Dropout rate.
|
345
|
+
resnet_eps (`float`, defaults to `1e-6`):
|
346
|
+
Epsilon value for normalization layers.
|
347
|
+
resnet_act_fn (`str`, defaults to `"swish"`):
|
348
|
+
Activation function to use.
|
349
|
+
resnet_groups (`int`, defaults to `32`):
|
350
|
+
Number of groups to separate the channels into for group normalization.
|
351
|
+
add_downsample (`bool`, defaults to `True`):
|
352
|
+
Whether or not to use a downsampling layer. If not used, output dimension would be same as input dimension.
|
353
|
+
compress_time (`bool`, defaults to `False`):
|
354
|
+
Whether or not to downsample across temporal dimension.
|
355
|
+
pad_mode (str, defaults to `"first"`):
|
356
|
+
Padding mode.
|
357
|
+
"""
|
358
|
+
|
359
|
+
_supports_gradient_checkpointing = True
|
360
|
+
|
361
|
+
def __init__(
|
362
|
+
self,
|
363
|
+
in_channels: int,
|
364
|
+
out_channels: int,
|
365
|
+
temb_channels: int,
|
366
|
+
dropout: float = 0.0,
|
367
|
+
num_layers: int = 1,
|
368
|
+
resnet_eps: float = 1e-6,
|
369
|
+
resnet_act_fn: str = "swish",
|
370
|
+
resnet_groups: int = 32,
|
371
|
+
add_downsample: bool = True,
|
372
|
+
downsample_padding: int = 0,
|
373
|
+
compress_time: bool = False,
|
374
|
+
pad_mode: str = "first",
|
375
|
+
):
|
376
|
+
super().__init__()
|
377
|
+
|
378
|
+
resnets = []
|
379
|
+
for i in range(num_layers):
|
380
|
+
in_channel = in_channels if i == 0 else out_channels
|
381
|
+
resnets.append(
|
382
|
+
CogVideoXResnetBlock3D(
|
383
|
+
in_channels=in_channel,
|
384
|
+
out_channels=out_channels,
|
385
|
+
dropout=dropout,
|
386
|
+
temb_channels=temb_channels,
|
387
|
+
groups=resnet_groups,
|
388
|
+
eps=resnet_eps,
|
389
|
+
non_linearity=resnet_act_fn,
|
390
|
+
pad_mode=pad_mode,
|
391
|
+
)
|
392
|
+
)
|
393
|
+
|
394
|
+
self.resnets = nn.ModuleList(resnets)
|
395
|
+
self.downsamplers = None
|
396
|
+
|
397
|
+
if add_downsample:
|
398
|
+
self.downsamplers = nn.ModuleList(
|
399
|
+
[
|
400
|
+
CogVideoXDownsample3D(
|
401
|
+
out_channels, out_channels, padding=downsample_padding, compress_time=compress_time
|
402
|
+
)
|
403
|
+
]
|
404
|
+
)
|
405
|
+
|
406
|
+
self.gradient_checkpointing = False
|
407
|
+
|
408
|
+
def forward(
|
409
|
+
self,
|
410
|
+
hidden_states: torch.Tensor,
|
411
|
+
temb: Optional[torch.Tensor] = None,
|
412
|
+
zq: Optional[torch.Tensor] = None,
|
413
|
+
conv_cache: Optional[Dict[str, torch.Tensor]] = None,
|
414
|
+
) -> torch.Tensor:
|
415
|
+
r"""Forward method of the `CogVideoXDownBlock3D` class."""
|
416
|
+
|
417
|
+
new_conv_cache = {}
|
418
|
+
conv_cache = conv_cache or {}
|
419
|
+
|
420
|
+
for i, resnet in enumerate(self.resnets):
|
421
|
+
conv_cache_key = f"resnet_{i}"
|
422
|
+
|
423
|
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
424
|
+
|
425
|
+
def create_custom_forward(module):
|
426
|
+
def create_forward(*inputs):
|
427
|
+
return module(*inputs)
|
428
|
+
|
429
|
+
return create_forward
|
430
|
+
|
431
|
+
hidden_states, new_conv_cache[conv_cache_key] = torch.utils.checkpoint.checkpoint(
|
432
|
+
create_custom_forward(resnet),
|
433
|
+
hidden_states,
|
434
|
+
temb,
|
435
|
+
zq,
|
436
|
+
conv_cache.get(conv_cache_key),
|
437
|
+
)
|
438
|
+
else:
|
439
|
+
hidden_states, new_conv_cache[conv_cache_key] = resnet(
|
440
|
+
hidden_states, temb, zq, conv_cache=conv_cache.get(conv_cache_key)
|
441
|
+
)
|
442
|
+
|
443
|
+
if self.downsamplers is not None:
|
444
|
+
for downsampler in self.downsamplers:
|
445
|
+
hidden_states = downsampler(hidden_states)
|
446
|
+
|
447
|
+
return hidden_states, new_conv_cache
|
448
|
+
|
449
|
+
|
450
|
+
class CogVideoXMidBlock3D(nn.Module):
|
451
|
+
r"""
|
452
|
+
A middle block used in the CogVideoX model.
|
453
|
+
|
454
|
+
Args:
|
455
|
+
in_channels (`int`):
|
456
|
+
Number of input channels.
|
457
|
+
temb_channels (`int`, defaults to `512`):
|
458
|
+
Number of time embedding channels.
|
459
|
+
dropout (`float`, defaults to `0.0`):
|
460
|
+
Dropout rate.
|
461
|
+
num_layers (`int`, defaults to `1`):
|
462
|
+
Number of resnet layers.
|
463
|
+
resnet_eps (`float`, defaults to `1e-6`):
|
464
|
+
Epsilon value for normalization layers.
|
465
|
+
resnet_act_fn (`str`, defaults to `"swish"`):
|
466
|
+
Activation function to use.
|
467
|
+
resnet_groups (`int`, defaults to `32`):
|
468
|
+
Number of groups to separate the channels into for group normalization.
|
469
|
+
spatial_norm_dim (`int`, *optional*):
|
470
|
+
The dimension to use for spatial norm if it is to be used instead of group norm.
|
471
|
+
pad_mode (str, defaults to `"first"`):
|
472
|
+
Padding mode.
|
473
|
+
"""
|
474
|
+
|
475
|
+
_supports_gradient_checkpointing = True
|
476
|
+
|
477
|
+
def __init__(
|
478
|
+
self,
|
479
|
+
in_channels: int,
|
480
|
+
temb_channels: int,
|
481
|
+
dropout: float = 0.0,
|
482
|
+
num_layers: int = 1,
|
483
|
+
resnet_eps: float = 1e-6,
|
484
|
+
resnet_act_fn: str = "swish",
|
485
|
+
resnet_groups: int = 32,
|
486
|
+
spatial_norm_dim: Optional[int] = None,
|
487
|
+
pad_mode: str = "first",
|
488
|
+
):
|
489
|
+
super().__init__()
|
490
|
+
|
491
|
+
resnets = []
|
492
|
+
for _ in range(num_layers):
|
493
|
+
resnets.append(
|
494
|
+
CogVideoXResnetBlock3D(
|
495
|
+
in_channels=in_channels,
|
496
|
+
out_channels=in_channels,
|
497
|
+
dropout=dropout,
|
498
|
+
temb_channels=temb_channels,
|
499
|
+
groups=resnet_groups,
|
500
|
+
eps=resnet_eps,
|
501
|
+
spatial_norm_dim=spatial_norm_dim,
|
502
|
+
non_linearity=resnet_act_fn,
|
503
|
+
pad_mode=pad_mode,
|
504
|
+
)
|
505
|
+
)
|
506
|
+
self.resnets = nn.ModuleList(resnets)
|
507
|
+
|
508
|
+
self.gradient_checkpointing = False
|
509
|
+
|
510
|
+
def forward(
|
511
|
+
self,
|
512
|
+
hidden_states: torch.Tensor,
|
513
|
+
temb: Optional[torch.Tensor] = None,
|
514
|
+
zq: Optional[torch.Tensor] = None,
|
515
|
+
conv_cache: Optional[Dict[str, torch.Tensor]] = None,
|
516
|
+
) -> torch.Tensor:
|
517
|
+
r"""Forward method of the `CogVideoXMidBlock3D` class."""
|
518
|
+
|
519
|
+
new_conv_cache = {}
|
520
|
+
conv_cache = conv_cache or {}
|
521
|
+
|
522
|
+
for i, resnet in enumerate(self.resnets):
|
523
|
+
conv_cache_key = f"resnet_{i}"
|
524
|
+
|
525
|
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
526
|
+
|
527
|
+
def create_custom_forward(module):
|
528
|
+
def create_forward(*inputs):
|
529
|
+
return module(*inputs)
|
530
|
+
|
531
|
+
return create_forward
|
532
|
+
|
533
|
+
hidden_states, new_conv_cache[conv_cache_key] = torch.utils.checkpoint.checkpoint(
|
534
|
+
create_custom_forward(resnet), hidden_states, temb, zq, conv_cache.get(conv_cache_key)
|
535
|
+
)
|
536
|
+
else:
|
537
|
+
hidden_states, new_conv_cache[conv_cache_key] = resnet(
|
538
|
+
hidden_states, temb, zq, conv_cache=conv_cache.get(conv_cache_key)
|
539
|
+
)
|
540
|
+
|
541
|
+
return hidden_states, new_conv_cache
|
542
|
+
|
543
|
+
|
544
|
+
class CogVideoXUpBlock3D(nn.Module):
|
545
|
+
r"""
|
546
|
+
An upsampling block used in the CogVideoX model.
|
547
|
+
|
548
|
+
Args:
|
549
|
+
in_channels (`int`):
|
550
|
+
Number of input channels.
|
551
|
+
out_channels (`int`, *optional*):
|
552
|
+
Number of output channels. If None, defaults to `in_channels`.
|
553
|
+
temb_channels (`int`, defaults to `512`):
|
554
|
+
Number of time embedding channels.
|
555
|
+
dropout (`float`, defaults to `0.0`):
|
556
|
+
Dropout rate.
|
557
|
+
num_layers (`int`, defaults to `1`):
|
558
|
+
Number of resnet layers.
|
559
|
+
resnet_eps (`float`, defaults to `1e-6`):
|
560
|
+
Epsilon value for normalization layers.
|
561
|
+
resnet_act_fn (`str`, defaults to `"swish"`):
|
562
|
+
Activation function to use.
|
563
|
+
resnet_groups (`int`, defaults to `32`):
|
564
|
+
Number of groups to separate the channels into for group normalization.
|
565
|
+
spatial_norm_dim (`int`, defaults to `16`):
|
566
|
+
The dimension to use for spatial norm if it is to be used instead of group norm.
|
567
|
+
add_upsample (`bool`, defaults to `True`):
|
568
|
+
Whether or not to use a upsampling layer. If not used, output dimension would be same as input dimension.
|
569
|
+
compress_time (`bool`, defaults to `False`):
|
570
|
+
Whether or not to downsample across temporal dimension.
|
571
|
+
pad_mode (str, defaults to `"first"`):
|
572
|
+
Padding mode.
|
573
|
+
"""
|
574
|
+
|
575
|
+
def __init__(
|
576
|
+
self,
|
577
|
+
in_channels: int,
|
578
|
+
out_channels: int,
|
579
|
+
temb_channels: int,
|
580
|
+
dropout: float = 0.0,
|
581
|
+
num_layers: int = 1,
|
582
|
+
resnet_eps: float = 1e-6,
|
583
|
+
resnet_act_fn: str = "swish",
|
584
|
+
resnet_groups: int = 32,
|
585
|
+
spatial_norm_dim: int = 16,
|
586
|
+
add_upsample: bool = True,
|
587
|
+
upsample_padding: int = 1,
|
588
|
+
compress_time: bool = False,
|
589
|
+
pad_mode: str = "first",
|
590
|
+
):
|
591
|
+
super().__init__()
|
592
|
+
|
593
|
+
resnets = []
|
594
|
+
for i in range(num_layers):
|
595
|
+
in_channel = in_channels if i == 0 else out_channels
|
596
|
+
resnets.append(
|
597
|
+
CogVideoXResnetBlock3D(
|
598
|
+
in_channels=in_channel,
|
599
|
+
out_channels=out_channels,
|
600
|
+
dropout=dropout,
|
601
|
+
temb_channels=temb_channels,
|
602
|
+
groups=resnet_groups,
|
603
|
+
eps=resnet_eps,
|
604
|
+
non_linearity=resnet_act_fn,
|
605
|
+
spatial_norm_dim=spatial_norm_dim,
|
606
|
+
pad_mode=pad_mode,
|
607
|
+
)
|
608
|
+
)
|
609
|
+
|
610
|
+
self.resnets = nn.ModuleList(resnets)
|
611
|
+
self.upsamplers = None
|
612
|
+
|
613
|
+
if add_upsample:
|
614
|
+
self.upsamplers = nn.ModuleList(
|
615
|
+
[
|
616
|
+
CogVideoXUpsample3D(
|
617
|
+
out_channels, out_channels, padding=upsample_padding, compress_time=compress_time
|
618
|
+
)
|
619
|
+
]
|
620
|
+
)
|
621
|
+
|
622
|
+
self.gradient_checkpointing = False
|
623
|
+
|
624
|
+
def forward(
|
625
|
+
self,
|
626
|
+
hidden_states: torch.Tensor,
|
627
|
+
temb: Optional[torch.Tensor] = None,
|
628
|
+
zq: Optional[torch.Tensor] = None,
|
629
|
+
conv_cache: Optional[Dict[str, torch.Tensor]] = None,
|
630
|
+
) -> torch.Tensor:
|
631
|
+
r"""Forward method of the `CogVideoXUpBlock3D` class."""
|
632
|
+
|
633
|
+
new_conv_cache = {}
|
634
|
+
conv_cache = conv_cache or {}
|
635
|
+
|
636
|
+
for i, resnet in enumerate(self.resnets):
|
637
|
+
conv_cache_key = f"resnet_{i}"
|
638
|
+
|
639
|
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
640
|
+
|
641
|
+
def create_custom_forward(module):
|
642
|
+
def create_forward(*inputs):
|
643
|
+
return module(*inputs)
|
644
|
+
|
645
|
+
return create_forward
|
646
|
+
|
647
|
+
hidden_states, new_conv_cache[conv_cache_key] = torch.utils.checkpoint.checkpoint(
|
648
|
+
create_custom_forward(resnet),
|
649
|
+
hidden_states,
|
650
|
+
temb,
|
651
|
+
zq,
|
652
|
+
conv_cache.get(conv_cache_key),
|
653
|
+
)
|
654
|
+
else:
|
655
|
+
hidden_states, new_conv_cache[conv_cache_key] = resnet(
|
656
|
+
hidden_states, temb, zq, conv_cache=conv_cache.get(conv_cache_key)
|
657
|
+
)
|
658
|
+
|
659
|
+
if self.upsamplers is not None:
|
660
|
+
for upsampler in self.upsamplers:
|
661
|
+
hidden_states = upsampler(hidden_states)
|
662
|
+
|
663
|
+
return hidden_states, new_conv_cache
|
664
|
+
|
665
|
+
|
666
|
+
class CogVideoXEncoder3D(nn.Module):
|
667
|
+
r"""
|
668
|
+
The `CogVideoXEncoder3D` layer of a variational autoencoder that encodes its input into a latent representation.
|
669
|
+
|
670
|
+
Args:
|
671
|
+
in_channels (`int`, *optional*, defaults to 3):
|
672
|
+
The number of input channels.
|
673
|
+
out_channels (`int`, *optional*, defaults to 3):
|
674
|
+
The number of output channels.
|
675
|
+
down_block_types (`Tuple[str, ...]`, *optional*, defaults to `("DownEncoderBlock2D",)`):
|
676
|
+
The types of down blocks to use. See `~diffusers.models.unet_2d_blocks.get_down_block` for available
|
677
|
+
options.
|
678
|
+
block_out_channels (`Tuple[int, ...]`, *optional*, defaults to `(64,)`):
|
679
|
+
The number of output channels for each block.
|
680
|
+
act_fn (`str`, *optional*, defaults to `"silu"`):
|
681
|
+
The activation function to use. See `~diffusers.models.activations.get_activation` for available options.
|
682
|
+
layers_per_block (`int`, *optional*, defaults to 2):
|
683
|
+
The number of layers per block.
|
684
|
+
norm_num_groups (`int`, *optional*, defaults to 32):
|
685
|
+
The number of groups for normalization.
|
686
|
+
"""
|
687
|
+
|
688
|
+
_supports_gradient_checkpointing = True
|
689
|
+
|
690
|
+
def __init__(
|
691
|
+
self,
|
692
|
+
in_channels: int = 3,
|
693
|
+
out_channels: int = 16,
|
694
|
+
down_block_types: Tuple[str, ...] = (
|
695
|
+
"CogVideoXDownBlock3D",
|
696
|
+
"CogVideoXDownBlock3D",
|
697
|
+
"CogVideoXDownBlock3D",
|
698
|
+
"CogVideoXDownBlock3D",
|
699
|
+
),
|
700
|
+
block_out_channels: Tuple[int, ...] = (128, 256, 256, 512),
|
701
|
+
layers_per_block: int = 3,
|
702
|
+
act_fn: str = "silu",
|
703
|
+
norm_eps: float = 1e-6,
|
704
|
+
norm_num_groups: int = 32,
|
705
|
+
dropout: float = 0.0,
|
706
|
+
pad_mode: str = "first",
|
707
|
+
temporal_compression_ratio: float = 4,
|
708
|
+
):
|
709
|
+
super().__init__()
|
710
|
+
|
711
|
+
# log2 of temporal_compress_times
|
712
|
+
temporal_compress_level = int(np.log2(temporal_compression_ratio))
|
713
|
+
|
714
|
+
self.conv_in = CogVideoXCausalConv3d(in_channels, block_out_channels[0], kernel_size=3, pad_mode=pad_mode)
|
715
|
+
self.down_blocks = nn.ModuleList([])
|
716
|
+
|
717
|
+
# down blocks
|
718
|
+
output_channel = block_out_channels[0]
|
719
|
+
for i, down_block_type in enumerate(down_block_types):
|
720
|
+
input_channel = output_channel
|
721
|
+
output_channel = block_out_channels[i]
|
722
|
+
is_final_block = i == len(block_out_channels) - 1
|
723
|
+
compress_time = i < temporal_compress_level
|
724
|
+
|
725
|
+
if down_block_type == "CogVideoXDownBlock3D":
|
726
|
+
down_block = CogVideoXDownBlock3D(
|
727
|
+
in_channels=input_channel,
|
728
|
+
out_channels=output_channel,
|
729
|
+
temb_channels=0,
|
730
|
+
dropout=dropout,
|
731
|
+
num_layers=layers_per_block,
|
732
|
+
resnet_eps=norm_eps,
|
733
|
+
resnet_act_fn=act_fn,
|
734
|
+
resnet_groups=norm_num_groups,
|
735
|
+
add_downsample=not is_final_block,
|
736
|
+
compress_time=compress_time,
|
737
|
+
)
|
738
|
+
else:
|
739
|
+
raise ValueError("Invalid `down_block_type` encountered. Must be `CogVideoXDownBlock3D`")
|
740
|
+
|
741
|
+
self.down_blocks.append(down_block)
|
742
|
+
|
743
|
+
# mid block
|
744
|
+
self.mid_block = CogVideoXMidBlock3D(
|
745
|
+
in_channels=block_out_channels[-1],
|
746
|
+
temb_channels=0,
|
747
|
+
dropout=dropout,
|
748
|
+
num_layers=2,
|
749
|
+
resnet_eps=norm_eps,
|
750
|
+
resnet_act_fn=act_fn,
|
751
|
+
resnet_groups=norm_num_groups,
|
752
|
+
pad_mode=pad_mode,
|
753
|
+
)
|
754
|
+
|
755
|
+
self.norm_out = nn.GroupNorm(norm_num_groups, block_out_channels[-1], eps=1e-6)
|
756
|
+
self.conv_act = nn.SiLU()
|
757
|
+
self.conv_out = CogVideoXCausalConv3d(
|
758
|
+
block_out_channels[-1], 2 * out_channels, kernel_size=3, pad_mode=pad_mode
|
759
|
+
)
|
760
|
+
|
761
|
+
self.gradient_checkpointing = False
|
762
|
+
|
763
|
+
def forward(
|
764
|
+
self,
|
765
|
+
sample: torch.Tensor,
|
766
|
+
temb: Optional[torch.Tensor] = None,
|
767
|
+
conv_cache: Optional[Dict[str, torch.Tensor]] = None,
|
768
|
+
) -> torch.Tensor:
|
769
|
+
r"""The forward method of the `CogVideoXEncoder3D` class."""
|
770
|
+
|
771
|
+
new_conv_cache = {}
|
772
|
+
conv_cache = conv_cache or {}
|
773
|
+
|
774
|
+
hidden_states, new_conv_cache["conv_in"] = self.conv_in(sample, conv_cache=conv_cache.get("conv_in"))
|
775
|
+
|
776
|
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
777
|
+
|
778
|
+
def create_custom_forward(module):
|
779
|
+
def custom_forward(*inputs):
|
780
|
+
return module(*inputs)
|
781
|
+
|
782
|
+
return custom_forward
|
783
|
+
|
784
|
+
# 1. Down
|
785
|
+
for i, down_block in enumerate(self.down_blocks):
|
786
|
+
conv_cache_key = f"down_block_{i}"
|
787
|
+
hidden_states, new_conv_cache[conv_cache_key] = torch.utils.checkpoint.checkpoint(
|
788
|
+
create_custom_forward(down_block),
|
789
|
+
hidden_states,
|
790
|
+
temb,
|
791
|
+
None,
|
792
|
+
conv_cache.get(conv_cache_key),
|
793
|
+
)
|
794
|
+
|
795
|
+
# 2. Mid
|
796
|
+
hidden_states, new_conv_cache["mid_block"] = torch.utils.checkpoint.checkpoint(
|
797
|
+
create_custom_forward(self.mid_block),
|
798
|
+
hidden_states,
|
799
|
+
temb,
|
800
|
+
None,
|
801
|
+
conv_cache.get("mid_block"),
|
802
|
+
)
|
803
|
+
else:
|
804
|
+
# 1. Down
|
805
|
+
for i, down_block in enumerate(self.down_blocks):
|
806
|
+
conv_cache_key = f"down_block_{i}"
|
807
|
+
hidden_states, new_conv_cache[conv_cache_key] = down_block(
|
808
|
+
hidden_states, temb, None, conv_cache.get(conv_cache_key)
|
809
|
+
)
|
810
|
+
|
811
|
+
# 2. Mid
|
812
|
+
hidden_states, new_conv_cache["mid_block"] = self.mid_block(
|
813
|
+
hidden_states, temb, None, conv_cache=conv_cache.get("mid_block")
|
814
|
+
)
|
815
|
+
|
816
|
+
# 3. Post-process
|
817
|
+
hidden_states = self.norm_out(hidden_states)
|
818
|
+
hidden_states = self.conv_act(hidden_states)
|
819
|
+
|
820
|
+
hidden_states, new_conv_cache["conv_out"] = self.conv_out(hidden_states, conv_cache=conv_cache.get("conv_out"))
|
821
|
+
|
822
|
+
return hidden_states, new_conv_cache
|
823
|
+
|
824
|
+
|
825
|
+
class CogVideoXDecoder3D(nn.Module):
|
826
|
+
r"""
|
827
|
+
The `CogVideoXDecoder3D` layer of a variational autoencoder that decodes its latent representation into an output
|
828
|
+
sample.
|
829
|
+
|
830
|
+
Args:
|
831
|
+
in_channels (`int`, *optional*, defaults to 3):
|
832
|
+
The number of input channels.
|
833
|
+
out_channels (`int`, *optional*, defaults to 3):
|
834
|
+
The number of output channels.
|
835
|
+
up_block_types (`Tuple[str, ...]`, *optional*, defaults to `("UpDecoderBlock2D",)`):
|
836
|
+
The types of up blocks to use. See `~diffusers.models.unet_2d_blocks.get_up_block` for available options.
|
837
|
+
block_out_channels (`Tuple[int, ...]`, *optional*, defaults to `(64,)`):
|
838
|
+
The number of output channels for each block.
|
839
|
+
act_fn (`str`, *optional*, defaults to `"silu"`):
|
840
|
+
The activation function to use. See `~diffusers.models.activations.get_activation` for available options.
|
841
|
+
layers_per_block (`int`, *optional*, defaults to 2):
|
842
|
+
The number of layers per block.
|
843
|
+
norm_num_groups (`int`, *optional*, defaults to 32):
|
844
|
+
The number of groups for normalization.
|
845
|
+
"""
|
846
|
+
|
847
|
+
_supports_gradient_checkpointing = True
|
848
|
+
|
849
|
+
def __init__(
|
850
|
+
self,
|
851
|
+
in_channels: int = 16,
|
852
|
+
out_channels: int = 3,
|
853
|
+
up_block_types: Tuple[str, ...] = (
|
854
|
+
"CogVideoXUpBlock3D",
|
855
|
+
"CogVideoXUpBlock3D",
|
856
|
+
"CogVideoXUpBlock3D",
|
857
|
+
"CogVideoXUpBlock3D",
|
858
|
+
),
|
859
|
+
block_out_channels: Tuple[int, ...] = (128, 256, 256, 512),
|
860
|
+
layers_per_block: int = 3,
|
861
|
+
act_fn: str = "silu",
|
862
|
+
norm_eps: float = 1e-6,
|
863
|
+
norm_num_groups: int = 32,
|
864
|
+
dropout: float = 0.0,
|
865
|
+
pad_mode: str = "first",
|
866
|
+
temporal_compression_ratio: float = 4,
|
867
|
+
):
|
868
|
+
super().__init__()
|
869
|
+
|
870
|
+
reversed_block_out_channels = list(reversed(block_out_channels))
|
871
|
+
|
872
|
+
self.conv_in = CogVideoXCausalConv3d(
|
873
|
+
in_channels, reversed_block_out_channels[0], kernel_size=3, pad_mode=pad_mode
|
874
|
+
)
|
875
|
+
|
876
|
+
# mid block
|
877
|
+
self.mid_block = CogVideoXMidBlock3D(
|
878
|
+
in_channels=reversed_block_out_channels[0],
|
879
|
+
temb_channels=0,
|
880
|
+
num_layers=2,
|
881
|
+
resnet_eps=norm_eps,
|
882
|
+
resnet_act_fn=act_fn,
|
883
|
+
resnet_groups=norm_num_groups,
|
884
|
+
spatial_norm_dim=in_channels,
|
885
|
+
pad_mode=pad_mode,
|
886
|
+
)
|
887
|
+
|
888
|
+
# up blocks
|
889
|
+
self.up_blocks = nn.ModuleList([])
|
890
|
+
|
891
|
+
output_channel = reversed_block_out_channels[0]
|
892
|
+
temporal_compress_level = int(np.log2(temporal_compression_ratio))
|
893
|
+
|
894
|
+
for i, up_block_type in enumerate(up_block_types):
|
895
|
+
prev_output_channel = output_channel
|
896
|
+
output_channel = reversed_block_out_channels[i]
|
897
|
+
is_final_block = i == len(block_out_channels) - 1
|
898
|
+
compress_time = i < temporal_compress_level
|
899
|
+
|
900
|
+
if up_block_type == "CogVideoXUpBlock3D":
|
901
|
+
up_block = CogVideoXUpBlock3D(
|
902
|
+
in_channels=prev_output_channel,
|
903
|
+
out_channels=output_channel,
|
904
|
+
temb_channels=0,
|
905
|
+
dropout=dropout,
|
906
|
+
num_layers=layers_per_block + 1,
|
907
|
+
resnet_eps=norm_eps,
|
908
|
+
resnet_act_fn=act_fn,
|
909
|
+
resnet_groups=norm_num_groups,
|
910
|
+
spatial_norm_dim=in_channels,
|
911
|
+
add_upsample=not is_final_block,
|
912
|
+
compress_time=compress_time,
|
913
|
+
pad_mode=pad_mode,
|
914
|
+
)
|
915
|
+
prev_output_channel = output_channel
|
916
|
+
else:
|
917
|
+
raise ValueError("Invalid `up_block_type` encountered. Must be `CogVideoXUpBlock3D`")
|
918
|
+
|
919
|
+
self.up_blocks.append(up_block)
|
920
|
+
|
921
|
+
self.norm_out = CogVideoXSpatialNorm3D(reversed_block_out_channels[-1], in_channels, groups=norm_num_groups)
|
922
|
+
self.conv_act = nn.SiLU()
|
923
|
+
self.conv_out = CogVideoXCausalConv3d(
|
924
|
+
reversed_block_out_channels[-1], out_channels, kernel_size=3, pad_mode=pad_mode
|
925
|
+
)
|
926
|
+
|
927
|
+
self.gradient_checkpointing = False
|
928
|
+
|
929
|
+
def forward(
|
930
|
+
self,
|
931
|
+
sample: torch.Tensor,
|
932
|
+
temb: Optional[torch.Tensor] = None,
|
933
|
+
conv_cache: Optional[Dict[str, torch.Tensor]] = None,
|
934
|
+
) -> torch.Tensor:
|
935
|
+
r"""The forward method of the `CogVideoXDecoder3D` class."""
|
936
|
+
|
937
|
+
new_conv_cache = {}
|
938
|
+
conv_cache = conv_cache or {}
|
939
|
+
|
940
|
+
hidden_states, new_conv_cache["conv_in"] = self.conv_in(sample, conv_cache=conv_cache.get("conv_in"))
|
941
|
+
|
942
|
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
943
|
+
|
944
|
+
def create_custom_forward(module):
|
945
|
+
def custom_forward(*inputs):
|
946
|
+
return module(*inputs)
|
947
|
+
|
948
|
+
return custom_forward
|
949
|
+
|
950
|
+
# 1. Mid
|
951
|
+
hidden_states, new_conv_cache["mid_block"] = torch.utils.checkpoint.checkpoint(
|
952
|
+
create_custom_forward(self.mid_block),
|
953
|
+
hidden_states,
|
954
|
+
temb,
|
955
|
+
sample,
|
956
|
+
conv_cache.get("mid_block"),
|
957
|
+
)
|
958
|
+
|
959
|
+
# 2. Up
|
960
|
+
for i, up_block in enumerate(self.up_blocks):
|
961
|
+
conv_cache_key = f"up_block_{i}"
|
962
|
+
hidden_states, new_conv_cache[conv_cache_key] = torch.utils.checkpoint.checkpoint(
|
963
|
+
create_custom_forward(up_block),
|
964
|
+
hidden_states,
|
965
|
+
temb,
|
966
|
+
sample,
|
967
|
+
conv_cache.get(conv_cache_key),
|
968
|
+
)
|
969
|
+
else:
|
970
|
+
# 1. Mid
|
971
|
+
hidden_states, new_conv_cache["mid_block"] = self.mid_block(
|
972
|
+
hidden_states, temb, sample, conv_cache=conv_cache.get("mid_block")
|
973
|
+
)
|
974
|
+
|
975
|
+
# 2. Up
|
976
|
+
for i, up_block in enumerate(self.up_blocks):
|
977
|
+
conv_cache_key = f"up_block_{i}"
|
978
|
+
hidden_states, new_conv_cache[conv_cache_key] = up_block(
|
979
|
+
hidden_states, temb, sample, conv_cache=conv_cache.get(conv_cache_key)
|
980
|
+
)
|
981
|
+
|
982
|
+
# 3. Post-process
|
983
|
+
hidden_states, new_conv_cache["norm_out"] = self.norm_out(
|
984
|
+
hidden_states, sample, conv_cache=conv_cache.get("norm_out")
|
985
|
+
)
|
986
|
+
hidden_states = self.conv_act(hidden_states)
|
987
|
+
hidden_states, new_conv_cache["conv_out"] = self.conv_out(hidden_states, conv_cache=conv_cache.get("conv_out"))
|
988
|
+
|
989
|
+
return hidden_states, new_conv_cache
|
990
|
+
|
991
|
+
|
992
|
+
class AutoencoderKLCogVideoX(ModelMixin, ConfigMixin, FromOriginalModelMixin):
|
993
|
+
r"""
|
994
|
+
A VAE model with KL loss for encoding images into latents and decoding latent representations into images. Used in
|
995
|
+
[CogVideoX](https://github.com/THUDM/CogVideo).
|
996
|
+
|
997
|
+
This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
|
998
|
+
for all models (such as downloading or saving).
|
999
|
+
|
1000
|
+
Parameters:
|
1001
|
+
in_channels (int, *optional*, defaults to 3): Number of channels in the input image.
|
1002
|
+
out_channels (int, *optional*, defaults to 3): Number of channels in the output.
|
1003
|
+
down_block_types (`Tuple[str]`, *optional*, defaults to `("DownEncoderBlock2D",)`):
|
1004
|
+
Tuple of downsample block types.
|
1005
|
+
up_block_types (`Tuple[str]`, *optional*, defaults to `("UpDecoderBlock2D",)`):
|
1006
|
+
Tuple of upsample block types.
|
1007
|
+
block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
|
1008
|
+
Tuple of block output channels.
|
1009
|
+
act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
|
1010
|
+
sample_size (`int`, *optional*, defaults to `32`): Sample input size.
|
1011
|
+
scaling_factor (`float`, *optional*, defaults to `1.15258426`):
|
1012
|
+
The component-wise standard deviation of the trained latent space computed using the first batch of the
|
1013
|
+
training set. This is used to scale the latent space to have unit variance when training the diffusion
|
1014
|
+
model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
|
1015
|
+
diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
|
1016
|
+
/ scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
|
1017
|
+
Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
|
1018
|
+
force_upcast (`bool`, *optional*, default to `True`):
|
1019
|
+
If enabled it will force the VAE to run in float32 for high image resolution pipelines, such as SD-XL. VAE
|
1020
|
+
can be fine-tuned / trained to a lower range without loosing too much precision in which case
|
1021
|
+
`force_upcast` can be set to `False` - see: https://huggingface.co/madebyollin/sdxl-vae-fp16-fix
|
1022
|
+
"""
|
1023
|
+
|
1024
|
+
_supports_gradient_checkpointing = True
|
1025
|
+
_no_split_modules = ["CogVideoXResnetBlock3D"]
|
1026
|
+
|
1027
|
+
@register_to_config
|
1028
|
+
def __init__(
|
1029
|
+
self,
|
1030
|
+
in_channels: int = 3,
|
1031
|
+
out_channels: int = 3,
|
1032
|
+
down_block_types: Tuple[str] = (
|
1033
|
+
"CogVideoXDownBlock3D",
|
1034
|
+
"CogVideoXDownBlock3D",
|
1035
|
+
"CogVideoXDownBlock3D",
|
1036
|
+
"CogVideoXDownBlock3D",
|
1037
|
+
),
|
1038
|
+
up_block_types: Tuple[str] = (
|
1039
|
+
"CogVideoXUpBlock3D",
|
1040
|
+
"CogVideoXUpBlock3D",
|
1041
|
+
"CogVideoXUpBlock3D",
|
1042
|
+
"CogVideoXUpBlock3D",
|
1043
|
+
),
|
1044
|
+
block_out_channels: Tuple[int] = (128, 256, 256, 512),
|
1045
|
+
latent_channels: int = 16,
|
1046
|
+
layers_per_block: int = 3,
|
1047
|
+
act_fn: str = "silu",
|
1048
|
+
norm_eps: float = 1e-6,
|
1049
|
+
norm_num_groups: int = 32,
|
1050
|
+
temporal_compression_ratio: float = 4,
|
1051
|
+
sample_height: int = 480,
|
1052
|
+
sample_width: int = 720,
|
1053
|
+
scaling_factor: float = 1.15258426,
|
1054
|
+
shift_factor: Optional[float] = None,
|
1055
|
+
latents_mean: Optional[Tuple[float]] = None,
|
1056
|
+
latents_std: Optional[Tuple[float]] = None,
|
1057
|
+
force_upcast: float = True,
|
1058
|
+
use_quant_conv: bool = False,
|
1059
|
+
use_post_quant_conv: bool = False,
|
1060
|
+
invert_scale_latents: bool = False,
|
1061
|
+
):
|
1062
|
+
super().__init__()
|
1063
|
+
|
1064
|
+
self.encoder = CogVideoXEncoder3D(
|
1065
|
+
in_channels=in_channels,
|
1066
|
+
out_channels=latent_channels,
|
1067
|
+
down_block_types=down_block_types,
|
1068
|
+
block_out_channels=block_out_channels,
|
1069
|
+
layers_per_block=layers_per_block,
|
1070
|
+
act_fn=act_fn,
|
1071
|
+
norm_eps=norm_eps,
|
1072
|
+
norm_num_groups=norm_num_groups,
|
1073
|
+
temporal_compression_ratio=temporal_compression_ratio,
|
1074
|
+
)
|
1075
|
+
self.decoder = CogVideoXDecoder3D(
|
1076
|
+
in_channels=latent_channels,
|
1077
|
+
out_channels=out_channels,
|
1078
|
+
up_block_types=up_block_types,
|
1079
|
+
block_out_channels=block_out_channels,
|
1080
|
+
layers_per_block=layers_per_block,
|
1081
|
+
act_fn=act_fn,
|
1082
|
+
norm_eps=norm_eps,
|
1083
|
+
norm_num_groups=norm_num_groups,
|
1084
|
+
temporal_compression_ratio=temporal_compression_ratio,
|
1085
|
+
)
|
1086
|
+
self.quant_conv = CogVideoXSafeConv3d(2 * out_channels, 2 * out_channels, 1) if use_quant_conv else None
|
1087
|
+
self.post_quant_conv = CogVideoXSafeConv3d(out_channels, out_channels, 1) if use_post_quant_conv else None
|
1088
|
+
|
1089
|
+
self.use_slicing = False
|
1090
|
+
self.use_tiling = False
|
1091
|
+
|
1092
|
+
# Can be increased to decode more latent frames at once, but comes at a reasonable memory cost and it is not
|
1093
|
+
# recommended because the temporal parts of the VAE, here, are tricky to understand.
|
1094
|
+
# If you decode X latent frames together, the number of output frames is:
|
1095
|
+
# (X + (2 conv cache) + (2 time upscale_1) + (4 time upscale_2) - (2 causal conv downscale)) => X + 6 frames
|
1096
|
+
#
|
1097
|
+
# Example with num_latent_frames_batch_size = 2:
|
1098
|
+
# - 12 latent frames: (0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11) are processed together
|
1099
|
+
# => (12 // 2 frame slices) * ((2 num_latent_frames_batch_size) + (2 conv cache) + (2 time upscale_1) + (4 time upscale_2) - (2 causal conv downscale))
|
1100
|
+
# => 6 * 8 = 48 frames
|
1101
|
+
# - 13 latent frames: (0, 1, 2) (special case), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12) are processed together
|
1102
|
+
# => (1 frame slice) * ((3 num_latent_frames_batch_size) + (2 conv cache) + (2 time upscale_1) + (4 time upscale_2) - (2 causal conv downscale)) +
|
1103
|
+
# ((13 - 3) // 2) * ((2 num_latent_frames_batch_size) + (2 conv cache) + (2 time upscale_1) + (4 time upscale_2) - (2 causal conv downscale))
|
1104
|
+
# => 1 * 9 + 5 * 8 = 49 frames
|
1105
|
+
# It has been implemented this way so as to not have "magic values" in the code base that would be hard to explain. Note that
|
1106
|
+
# setting it to anything other than 2 would give poor results because the VAE hasn't been trained to be adaptive with different
|
1107
|
+
# number of temporal frames.
|
1108
|
+
self.num_latent_frames_batch_size = 2
|
1109
|
+
self.num_sample_frames_batch_size = 8
|
1110
|
+
|
1111
|
+
# We make the minimum height and width of sample for tiling half that of the generally supported
|
1112
|
+
self.tile_sample_min_height = sample_height // 2
|
1113
|
+
self.tile_sample_min_width = sample_width // 2
|
1114
|
+
self.tile_latent_min_height = int(
|
1115
|
+
self.tile_sample_min_height / (2 ** (len(self.config.block_out_channels) - 1))
|
1116
|
+
)
|
1117
|
+
self.tile_latent_min_width = int(self.tile_sample_min_width / (2 ** (len(self.config.block_out_channels) - 1)))
|
1118
|
+
|
1119
|
+
# These are experimental overlap factors that were chosen based on experimentation and seem to work best for
|
1120
|
+
# 720x480 (WxH) resolution. The above resolution is the strongly recommended generation resolution in CogVideoX
|
1121
|
+
# and so the tiling implementation has only been tested on those specific resolutions.
|
1122
|
+
self.tile_overlap_factor_height = 1 / 6
|
1123
|
+
self.tile_overlap_factor_width = 1 / 5
|
1124
|
+
|
1125
|
+
def _set_gradient_checkpointing(self, module, value=False):
|
1126
|
+
if isinstance(module, (CogVideoXEncoder3D, CogVideoXDecoder3D)):
|
1127
|
+
module.gradient_checkpointing = value
|
1128
|
+
|
1129
|
+
def enable_tiling(
|
1130
|
+
self,
|
1131
|
+
tile_sample_min_height: Optional[int] = None,
|
1132
|
+
tile_sample_min_width: Optional[int] = None,
|
1133
|
+
tile_overlap_factor_height: Optional[float] = None,
|
1134
|
+
tile_overlap_factor_width: Optional[float] = None,
|
1135
|
+
) -> None:
|
1136
|
+
r"""
|
1137
|
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
1138
|
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
1139
|
+
processing larger images.
|
1140
|
+
|
1141
|
+
Args:
|
1142
|
+
tile_sample_min_height (`int`, *optional*):
|
1143
|
+
The minimum height required for a sample to be separated into tiles across the height dimension.
|
1144
|
+
tile_sample_min_width (`int`, *optional*):
|
1145
|
+
The minimum width required for a sample to be separated into tiles across the width dimension.
|
1146
|
+
tile_overlap_factor_height (`int`, *optional*):
|
1147
|
+
The minimum amount of overlap between two consecutive vertical tiles. This is to ensure that there are
|
1148
|
+
no tiling artifacts produced across the height dimension. Must be between 0 and 1. Setting a higher
|
1149
|
+
value might cause more tiles to be processed leading to slow down of the decoding process.
|
1150
|
+
tile_overlap_factor_width (`int`, *optional*):
|
1151
|
+
The minimum amount of overlap between two consecutive horizontal tiles. This is to ensure that there
|
1152
|
+
are no tiling artifacts produced across the width dimension. Must be between 0 and 1. Setting a higher
|
1153
|
+
value might cause more tiles to be processed leading to slow down of the decoding process.
|
1154
|
+
"""
|
1155
|
+
self.use_tiling = True
|
1156
|
+
self.tile_sample_min_height = tile_sample_min_height or self.tile_sample_min_height
|
1157
|
+
self.tile_sample_min_width = tile_sample_min_width or self.tile_sample_min_width
|
1158
|
+
self.tile_latent_min_height = int(
|
1159
|
+
self.tile_sample_min_height / (2 ** (len(self.config.block_out_channels) - 1))
|
1160
|
+
)
|
1161
|
+
self.tile_latent_min_width = int(self.tile_sample_min_width / (2 ** (len(self.config.block_out_channels) - 1)))
|
1162
|
+
self.tile_overlap_factor_height = tile_overlap_factor_height or self.tile_overlap_factor_height
|
1163
|
+
self.tile_overlap_factor_width = tile_overlap_factor_width or self.tile_overlap_factor_width
|
1164
|
+
|
1165
|
+
def disable_tiling(self) -> None:
|
1166
|
+
r"""
|
1167
|
+
Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
|
1168
|
+
decoding in one step.
|
1169
|
+
"""
|
1170
|
+
self.use_tiling = False
|
1171
|
+
|
1172
|
+
def enable_slicing(self) -> None:
|
1173
|
+
r"""
|
1174
|
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
1175
|
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
1176
|
+
"""
|
1177
|
+
self.use_slicing = True
|
1178
|
+
|
1179
|
+
def disable_slicing(self) -> None:
|
1180
|
+
r"""
|
1181
|
+
Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
|
1182
|
+
decoding in one step.
|
1183
|
+
"""
|
1184
|
+
self.use_slicing = False
|
1185
|
+
|
1186
|
+
def _encode(self, x: torch.Tensor) -> torch.Tensor:
|
1187
|
+
batch_size, num_channels, num_frames, height, width = x.shape
|
1188
|
+
|
1189
|
+
if self.use_tiling and (width > self.tile_sample_min_width or height > self.tile_sample_min_height):
|
1190
|
+
return self.tiled_encode(x)
|
1191
|
+
|
1192
|
+
frame_batch_size = self.num_sample_frames_batch_size
|
1193
|
+
# Note: We expect the number of frames to be either `1` or `frame_batch_size * k` or `frame_batch_size * k + 1` for some k.
|
1194
|
+
# As the extra single frame is handled inside the loop, it is not required to round up here.
|
1195
|
+
num_batches = max(num_frames // frame_batch_size, 1)
|
1196
|
+
conv_cache = None
|
1197
|
+
enc = []
|
1198
|
+
|
1199
|
+
for i in range(num_batches):
|
1200
|
+
remaining_frames = num_frames % frame_batch_size
|
1201
|
+
start_frame = frame_batch_size * i + (0 if i == 0 else remaining_frames)
|
1202
|
+
end_frame = frame_batch_size * (i + 1) + remaining_frames
|
1203
|
+
x_intermediate = x[:, :, start_frame:end_frame]
|
1204
|
+
x_intermediate, conv_cache = self.encoder(x_intermediate, conv_cache=conv_cache)
|
1205
|
+
if self.quant_conv is not None:
|
1206
|
+
x_intermediate = self.quant_conv(x_intermediate)
|
1207
|
+
enc.append(x_intermediate)
|
1208
|
+
|
1209
|
+
enc = torch.cat(enc, dim=2)
|
1210
|
+
return enc
|
1211
|
+
|
1212
|
+
@apply_forward_hook
|
1213
|
+
def encode(
|
1214
|
+
self, x: torch.Tensor, return_dict: bool = True
|
1215
|
+
) -> Union[AutoencoderKLOutput, Tuple[DiagonalGaussianDistribution]]:
|
1216
|
+
"""
|
1217
|
+
Encode a batch of images into latents.
|
1218
|
+
|
1219
|
+
Args:
|
1220
|
+
x (`torch.Tensor`): Input batch of images.
|
1221
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
1222
|
+
Whether to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.
|
1223
|
+
|
1224
|
+
Returns:
|
1225
|
+
The latent representations of the encoded videos. If `return_dict` is True, a
|
1226
|
+
[`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain `tuple` is returned.
|
1227
|
+
"""
|
1228
|
+
if self.use_slicing and x.shape[0] > 1:
|
1229
|
+
encoded_slices = [self._encode(x_slice) for x_slice in x.split(1)]
|
1230
|
+
h = torch.cat(encoded_slices)
|
1231
|
+
else:
|
1232
|
+
h = self._encode(x)
|
1233
|
+
|
1234
|
+
posterior = DiagonalGaussianDistribution(h)
|
1235
|
+
|
1236
|
+
if not return_dict:
|
1237
|
+
return (posterior,)
|
1238
|
+
return AutoencoderKLOutput(latent_dist=posterior)
|
1239
|
+
|
1240
|
+
def _decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]:
|
1241
|
+
batch_size, num_channels, num_frames, height, width = z.shape
|
1242
|
+
|
1243
|
+
if self.use_tiling and (width > self.tile_latent_min_width or height > self.tile_latent_min_height):
|
1244
|
+
return self.tiled_decode(z, return_dict=return_dict)
|
1245
|
+
|
1246
|
+
frame_batch_size = self.num_latent_frames_batch_size
|
1247
|
+
num_batches = max(num_frames // frame_batch_size, 1)
|
1248
|
+
conv_cache = None
|
1249
|
+
dec = []
|
1250
|
+
|
1251
|
+
for i in range(num_batches):
|
1252
|
+
remaining_frames = num_frames % frame_batch_size
|
1253
|
+
start_frame = frame_batch_size * i + (0 if i == 0 else remaining_frames)
|
1254
|
+
end_frame = frame_batch_size * (i + 1) + remaining_frames
|
1255
|
+
z_intermediate = z[:, :, start_frame:end_frame]
|
1256
|
+
if self.post_quant_conv is not None:
|
1257
|
+
z_intermediate = self.post_quant_conv(z_intermediate)
|
1258
|
+
z_intermediate, conv_cache = self.decoder(z_intermediate, conv_cache=conv_cache)
|
1259
|
+
dec.append(z_intermediate)
|
1260
|
+
|
1261
|
+
dec = torch.cat(dec, dim=2)
|
1262
|
+
|
1263
|
+
if not return_dict:
|
1264
|
+
return (dec,)
|
1265
|
+
|
1266
|
+
return DecoderOutput(sample=dec)
|
1267
|
+
|
1268
|
+
@apply_forward_hook
|
1269
|
+
def decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]:
|
1270
|
+
"""
|
1271
|
+
Decode a batch of images.
|
1272
|
+
|
1273
|
+
Args:
|
1274
|
+
z (`torch.Tensor`): Input batch of latent vectors.
|
1275
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
1276
|
+
Whether to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.
|
1277
|
+
|
1278
|
+
Returns:
|
1279
|
+
[`~models.vae.DecoderOutput`] or `tuple`:
|
1280
|
+
If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
|
1281
|
+
returned.
|
1282
|
+
"""
|
1283
|
+
if self.use_slicing and z.shape[0] > 1:
|
1284
|
+
decoded_slices = [self._decode(z_slice).sample for z_slice in z.split(1)]
|
1285
|
+
decoded = torch.cat(decoded_slices)
|
1286
|
+
else:
|
1287
|
+
decoded = self._decode(z).sample
|
1288
|
+
|
1289
|
+
if not return_dict:
|
1290
|
+
return (decoded,)
|
1291
|
+
return DecoderOutput(sample=decoded)
|
1292
|
+
|
1293
|
+
def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
|
1294
|
+
blend_extent = min(a.shape[3], b.shape[3], blend_extent)
|
1295
|
+
for y in range(blend_extent):
|
1296
|
+
b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, :, y, :] * (
|
1297
|
+
y / blend_extent
|
1298
|
+
)
|
1299
|
+
return b
|
1300
|
+
|
1301
|
+
def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
|
1302
|
+
blend_extent = min(a.shape[4], b.shape[4], blend_extent)
|
1303
|
+
for x in range(blend_extent):
|
1304
|
+
b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, :, x] * (
|
1305
|
+
x / blend_extent
|
1306
|
+
)
|
1307
|
+
return b
|
1308
|
+
|
1309
|
+
def tiled_encode(self, x: torch.Tensor) -> torch.Tensor:
|
1310
|
+
r"""Encode a batch of images using a tiled encoder.
|
1311
|
+
|
1312
|
+
When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
|
1313
|
+
steps. This is useful to keep memory use constant regardless of image size. The end result of tiled encoding is
|
1314
|
+
different from non-tiled encoding because each tile uses a different encoder. To avoid tiling artifacts, the
|
1315
|
+
tiles overlap and are blended together to form a smooth output. You may still see tile-sized changes in the
|
1316
|
+
output, but they should be much less noticeable.
|
1317
|
+
|
1318
|
+
Args:
|
1319
|
+
x (`torch.Tensor`): Input batch of videos.
|
1320
|
+
|
1321
|
+
Returns:
|
1322
|
+
`torch.Tensor`:
|
1323
|
+
The latent representation of the encoded videos.
|
1324
|
+
"""
|
1325
|
+
# For a rough memory estimate, take a look at the `tiled_decode` method.
|
1326
|
+
batch_size, num_channels, num_frames, height, width = x.shape
|
1327
|
+
|
1328
|
+
overlap_height = int(self.tile_sample_min_height * (1 - self.tile_overlap_factor_height))
|
1329
|
+
overlap_width = int(self.tile_sample_min_width * (1 - self.tile_overlap_factor_width))
|
1330
|
+
blend_extent_height = int(self.tile_latent_min_height * self.tile_overlap_factor_height)
|
1331
|
+
blend_extent_width = int(self.tile_latent_min_width * self.tile_overlap_factor_width)
|
1332
|
+
row_limit_height = self.tile_latent_min_height - blend_extent_height
|
1333
|
+
row_limit_width = self.tile_latent_min_width - blend_extent_width
|
1334
|
+
frame_batch_size = self.num_sample_frames_batch_size
|
1335
|
+
|
1336
|
+
# Split x into overlapping tiles and encode them separately.
|
1337
|
+
# The tiles have an overlap to avoid seams between tiles.
|
1338
|
+
rows = []
|
1339
|
+
for i in range(0, height, overlap_height):
|
1340
|
+
row = []
|
1341
|
+
for j in range(0, width, overlap_width):
|
1342
|
+
# Note: We expect the number of frames to be either `1` or `frame_batch_size * k` or `frame_batch_size * k + 1` for some k.
|
1343
|
+
# As the extra single frame is handled inside the loop, it is not required to round up here.
|
1344
|
+
num_batches = max(num_frames // frame_batch_size, 1)
|
1345
|
+
conv_cache = None
|
1346
|
+
time = []
|
1347
|
+
|
1348
|
+
for k in range(num_batches):
|
1349
|
+
remaining_frames = num_frames % frame_batch_size
|
1350
|
+
start_frame = frame_batch_size * k + (0 if k == 0 else remaining_frames)
|
1351
|
+
end_frame = frame_batch_size * (k + 1) + remaining_frames
|
1352
|
+
tile = x[
|
1353
|
+
:,
|
1354
|
+
:,
|
1355
|
+
start_frame:end_frame,
|
1356
|
+
i : i + self.tile_sample_min_height,
|
1357
|
+
j : j + self.tile_sample_min_width,
|
1358
|
+
]
|
1359
|
+
tile, conv_cache = self.encoder(tile, conv_cache=conv_cache)
|
1360
|
+
if self.quant_conv is not None:
|
1361
|
+
tile = self.quant_conv(tile)
|
1362
|
+
time.append(tile)
|
1363
|
+
|
1364
|
+
row.append(torch.cat(time, dim=2))
|
1365
|
+
rows.append(row)
|
1366
|
+
|
1367
|
+
result_rows = []
|
1368
|
+
for i, row in enumerate(rows):
|
1369
|
+
result_row = []
|
1370
|
+
for j, tile in enumerate(row):
|
1371
|
+
# blend the above tile and the left tile
|
1372
|
+
# to the current tile and add the current tile to the result row
|
1373
|
+
if i > 0:
|
1374
|
+
tile = self.blend_v(rows[i - 1][j], tile, blend_extent_height)
|
1375
|
+
if j > 0:
|
1376
|
+
tile = self.blend_h(row[j - 1], tile, blend_extent_width)
|
1377
|
+
result_row.append(tile[:, :, :, :row_limit_height, :row_limit_width])
|
1378
|
+
result_rows.append(torch.cat(result_row, dim=4))
|
1379
|
+
|
1380
|
+
enc = torch.cat(result_rows, dim=3)
|
1381
|
+
return enc
|
1382
|
+
|
1383
|
+
def tiled_decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]:
|
1384
|
+
r"""
|
1385
|
+
Decode a batch of images using a tiled decoder.
|
1386
|
+
|
1387
|
+
Args:
|
1388
|
+
z (`torch.Tensor`): Input batch of latent vectors.
|
1389
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
1390
|
+
Whether or not to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.
|
1391
|
+
|
1392
|
+
Returns:
|
1393
|
+
[`~models.vae.DecoderOutput`] or `tuple`:
|
1394
|
+
If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
|
1395
|
+
returned.
|
1396
|
+
"""
|
1397
|
+
# Rough memory assessment:
|
1398
|
+
# - In CogVideoX-2B, there are a total of 24 CausalConv3d layers.
|
1399
|
+
# - The biggest intermediate dimensions are: [1, 128, 9, 480, 720].
|
1400
|
+
# - Assume fp16 (2 bytes per value).
|
1401
|
+
# Memory required: 1 * 128 * 9 * 480 * 720 * 24 * 2 / 1024**3 = 17.8 GB
|
1402
|
+
#
|
1403
|
+
# Memory assessment when using tiling:
|
1404
|
+
# - Assume everything as above but now HxW is 240x360 by tiling in half
|
1405
|
+
# Memory required: 1 * 128 * 9 * 240 * 360 * 24 * 2 / 1024**3 = 4.5 GB
|
1406
|
+
|
1407
|
+
batch_size, num_channels, num_frames, height, width = z.shape
|
1408
|
+
|
1409
|
+
overlap_height = int(self.tile_latent_min_height * (1 - self.tile_overlap_factor_height))
|
1410
|
+
overlap_width = int(self.tile_latent_min_width * (1 - self.tile_overlap_factor_width))
|
1411
|
+
blend_extent_height = int(self.tile_sample_min_height * self.tile_overlap_factor_height)
|
1412
|
+
blend_extent_width = int(self.tile_sample_min_width * self.tile_overlap_factor_width)
|
1413
|
+
row_limit_height = self.tile_sample_min_height - blend_extent_height
|
1414
|
+
row_limit_width = self.tile_sample_min_width - blend_extent_width
|
1415
|
+
frame_batch_size = self.num_latent_frames_batch_size
|
1416
|
+
|
1417
|
+
# Split z into overlapping tiles and decode them separately.
|
1418
|
+
# The tiles have an overlap to avoid seams between tiles.
|
1419
|
+
rows = []
|
1420
|
+
for i in range(0, height, overlap_height):
|
1421
|
+
row = []
|
1422
|
+
for j in range(0, width, overlap_width):
|
1423
|
+
num_batches = max(num_frames // frame_batch_size, 1)
|
1424
|
+
conv_cache = None
|
1425
|
+
time = []
|
1426
|
+
|
1427
|
+
for k in range(num_batches):
|
1428
|
+
remaining_frames = num_frames % frame_batch_size
|
1429
|
+
start_frame = frame_batch_size * k + (0 if k == 0 else remaining_frames)
|
1430
|
+
end_frame = frame_batch_size * (k + 1) + remaining_frames
|
1431
|
+
tile = z[
|
1432
|
+
:,
|
1433
|
+
:,
|
1434
|
+
start_frame:end_frame,
|
1435
|
+
i : i + self.tile_latent_min_height,
|
1436
|
+
j : j + self.tile_latent_min_width,
|
1437
|
+
]
|
1438
|
+
if self.post_quant_conv is not None:
|
1439
|
+
tile = self.post_quant_conv(tile)
|
1440
|
+
tile, conv_cache = self.decoder(tile, conv_cache=conv_cache)
|
1441
|
+
time.append(tile)
|
1442
|
+
|
1443
|
+
row.append(torch.cat(time, dim=2))
|
1444
|
+
rows.append(row)
|
1445
|
+
|
1446
|
+
result_rows = []
|
1447
|
+
for i, row in enumerate(rows):
|
1448
|
+
result_row = []
|
1449
|
+
for j, tile in enumerate(row):
|
1450
|
+
# blend the above tile and the left tile
|
1451
|
+
# to the current tile and add the current tile to the result row
|
1452
|
+
if i > 0:
|
1453
|
+
tile = self.blend_v(rows[i - 1][j], tile, blend_extent_height)
|
1454
|
+
if j > 0:
|
1455
|
+
tile = self.blend_h(row[j - 1], tile, blend_extent_width)
|
1456
|
+
result_row.append(tile[:, :, :, :row_limit_height, :row_limit_width])
|
1457
|
+
result_rows.append(torch.cat(result_row, dim=4))
|
1458
|
+
|
1459
|
+
dec = torch.cat(result_rows, dim=3)
|
1460
|
+
|
1461
|
+
if not return_dict:
|
1462
|
+
return (dec,)
|
1463
|
+
|
1464
|
+
return DecoderOutput(sample=dec)
|
1465
|
+
|
1466
|
+
def forward(
|
1467
|
+
self,
|
1468
|
+
sample: torch.Tensor,
|
1469
|
+
sample_posterior: bool = False,
|
1470
|
+
return_dict: bool = True,
|
1471
|
+
generator: Optional[torch.Generator] = None,
|
1472
|
+
) -> Union[torch.Tensor, torch.Tensor]:
|
1473
|
+
x = sample
|
1474
|
+
posterior = self.encode(x).latent_dist
|
1475
|
+
if sample_posterior:
|
1476
|
+
z = posterior.sample(generator=generator)
|
1477
|
+
else:
|
1478
|
+
z = posterior.mode()
|
1479
|
+
dec = self.decode(z).sample
|
1480
|
+
if not return_dict:
|
1481
|
+
return (dec,)
|
1482
|
+
return DecoderOutput(sample=dec)
|