diffusers 0.33.0__py3-none-any.whl → 0.34.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- diffusers/__init__.py +48 -1
- diffusers/commands/__init__.py +1 -1
- diffusers/commands/diffusers_cli.py +1 -1
- diffusers/commands/env.py +1 -1
- diffusers/commands/fp16_safetensors.py +1 -1
- diffusers/dependency_versions_check.py +1 -1
- diffusers/dependency_versions_table.py +1 -1
- diffusers/experimental/rl/value_guided_sampling.py +1 -1
- diffusers/hooks/faster_cache.py +2 -2
- diffusers/hooks/group_offloading.py +128 -29
- diffusers/hooks/hooks.py +2 -2
- diffusers/hooks/layerwise_casting.py +3 -3
- diffusers/hooks/pyramid_attention_broadcast.py +1 -1
- diffusers/image_processor.py +7 -2
- diffusers/loaders/__init__.py +4 -0
- diffusers/loaders/ip_adapter.py +5 -14
- diffusers/loaders/lora_base.py +212 -111
- diffusers/loaders/lora_conversion_utils.py +275 -34
- diffusers/loaders/lora_pipeline.py +1554 -819
- diffusers/loaders/peft.py +52 -109
- diffusers/loaders/single_file.py +2 -2
- diffusers/loaders/single_file_model.py +20 -4
- diffusers/loaders/single_file_utils.py +225 -5
- diffusers/loaders/textual_inversion.py +3 -2
- diffusers/loaders/transformer_flux.py +1 -1
- diffusers/loaders/transformer_sd3.py +2 -2
- diffusers/loaders/unet.py +2 -16
- diffusers/loaders/unet_loader_utils.py +1 -1
- diffusers/loaders/utils.py +1 -1
- diffusers/models/__init__.py +15 -1
- diffusers/models/activations.py +5 -5
- diffusers/models/adapter.py +2 -3
- diffusers/models/attention.py +4 -4
- diffusers/models/attention_flax.py +10 -10
- diffusers/models/attention_processor.py +14 -10
- diffusers/models/auto_model.py +47 -10
- diffusers/models/autoencoders/__init__.py +1 -0
- diffusers/models/autoencoders/autoencoder_asym_kl.py +4 -4
- diffusers/models/autoencoders/autoencoder_dc.py +3 -3
- diffusers/models/autoencoders/autoencoder_kl.py +4 -4
- diffusers/models/autoencoders/autoencoder_kl_allegro.py +4 -4
- diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +6 -6
- diffusers/models/autoencoders/autoencoder_kl_cosmos.py +1108 -0
- diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py +2 -2
- diffusers/models/autoencoders/autoencoder_kl_ltx.py +3 -3
- diffusers/models/autoencoders/autoencoder_kl_magvit.py +4 -4
- diffusers/models/autoencoders/autoencoder_kl_mochi.py +3 -3
- diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +4 -4
- diffusers/models/autoencoders/autoencoder_kl_wan.py +256 -22
- diffusers/models/autoencoders/autoencoder_oobleck.py +1 -1
- diffusers/models/autoencoders/autoencoder_tiny.py +3 -3
- diffusers/models/autoencoders/consistency_decoder_vae.py +1 -1
- diffusers/models/autoencoders/vae.py +13 -2
- diffusers/models/autoencoders/vq_model.py +2 -2
- diffusers/models/cache_utils.py +1 -1
- diffusers/models/controlnet.py +1 -1
- diffusers/models/controlnet_flux.py +1 -1
- diffusers/models/controlnet_sd3.py +1 -1
- diffusers/models/controlnet_sparsectrl.py +1 -1
- diffusers/models/controlnets/__init__.py +1 -0
- diffusers/models/controlnets/controlnet.py +3 -3
- diffusers/models/controlnets/controlnet_flax.py +1 -1
- diffusers/models/controlnets/controlnet_flux.py +16 -15
- diffusers/models/controlnets/controlnet_hunyuan.py +2 -2
- diffusers/models/controlnets/controlnet_sana.py +290 -0
- diffusers/models/controlnets/controlnet_sd3.py +1 -1
- diffusers/models/controlnets/controlnet_sparsectrl.py +2 -2
- diffusers/models/controlnets/controlnet_union.py +1 -1
- diffusers/models/controlnets/controlnet_xs.py +7 -7
- diffusers/models/controlnets/multicontrolnet.py +4 -5
- diffusers/models/controlnets/multicontrolnet_union.py +5 -6
- diffusers/models/downsampling.py +2 -2
- diffusers/models/embeddings.py +10 -12
- diffusers/models/embeddings_flax.py +2 -2
- diffusers/models/lora.py +3 -3
- diffusers/models/modeling_utils.py +44 -14
- diffusers/models/normalization.py +4 -4
- diffusers/models/resnet.py +2 -2
- diffusers/models/resnet_flax.py +1 -1
- diffusers/models/transformers/__init__.py +5 -0
- diffusers/models/transformers/auraflow_transformer_2d.py +70 -24
- diffusers/models/transformers/cogvideox_transformer_3d.py +1 -1
- diffusers/models/transformers/consisid_transformer_3d.py +1 -1
- diffusers/models/transformers/dit_transformer_2d.py +2 -2
- diffusers/models/transformers/dual_transformer_2d.py +1 -1
- diffusers/models/transformers/hunyuan_transformer_2d.py +2 -2
- diffusers/models/transformers/latte_transformer_3d.py +4 -5
- diffusers/models/transformers/lumina_nextdit2d.py +2 -2
- diffusers/models/transformers/pixart_transformer_2d.py +3 -3
- diffusers/models/transformers/prior_transformer.py +1 -1
- diffusers/models/transformers/sana_transformer.py +8 -3
- diffusers/models/transformers/stable_audio_transformer.py +5 -9
- diffusers/models/transformers/t5_film_transformer.py +3 -3
- diffusers/models/transformers/transformer_2d.py +1 -1
- diffusers/models/transformers/transformer_allegro.py +1 -1
- diffusers/models/transformers/transformer_chroma.py +742 -0
- diffusers/models/transformers/transformer_cogview3plus.py +5 -10
- diffusers/models/transformers/transformer_cogview4.py +317 -25
- diffusers/models/transformers/transformer_cosmos.py +579 -0
- diffusers/models/transformers/transformer_flux.py +9 -11
- diffusers/models/transformers/transformer_hidream_image.py +942 -0
- diffusers/models/transformers/transformer_hunyuan_video.py +6 -8
- diffusers/models/transformers/transformer_hunyuan_video_framepack.py +416 -0
- diffusers/models/transformers/transformer_ltx.py +2 -2
- diffusers/models/transformers/transformer_lumina2.py +1 -1
- diffusers/models/transformers/transformer_mochi.py +1 -1
- diffusers/models/transformers/transformer_omnigen.py +2 -2
- diffusers/models/transformers/transformer_sd3.py +7 -7
- diffusers/models/transformers/transformer_temporal.py +1 -1
- diffusers/models/transformers/transformer_wan.py +24 -8
- diffusers/models/transformers/transformer_wan_vace.py +393 -0
- diffusers/models/unets/unet_1d.py +1 -1
- diffusers/models/unets/unet_1d_blocks.py +1 -1
- diffusers/models/unets/unet_2d.py +1 -1
- diffusers/models/unets/unet_2d_blocks.py +1 -1
- diffusers/models/unets/unet_2d_blocks_flax.py +8 -7
- diffusers/models/unets/unet_2d_condition.py +2 -2
- diffusers/models/unets/unet_2d_condition_flax.py +2 -2
- diffusers/models/unets/unet_3d_blocks.py +1 -1
- diffusers/models/unets/unet_3d_condition.py +3 -3
- diffusers/models/unets/unet_i2vgen_xl.py +3 -3
- diffusers/models/unets/unet_kandinsky3.py +1 -1
- diffusers/models/unets/unet_motion_model.py +2 -2
- diffusers/models/unets/unet_stable_cascade.py +1 -1
- diffusers/models/upsampling.py +2 -2
- diffusers/models/vae_flax.py +2 -2
- diffusers/models/vq_model.py +1 -1
- diffusers/pipelines/__init__.py +37 -6
- diffusers/pipelines/allegro/pipeline_allegro.py +11 -11
- diffusers/pipelines/amused/pipeline_amused.py +7 -6
- diffusers/pipelines/amused/pipeline_amused_img2img.py +6 -5
- diffusers/pipelines/amused/pipeline_amused_inpaint.py +6 -5
- diffusers/pipelines/animatediff/pipeline_animatediff.py +6 -6
- diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +6 -6
- diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +16 -15
- diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +6 -6
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +5 -5
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +5 -5
- diffusers/pipelines/audioldm/pipeline_audioldm.py +8 -7
- diffusers/pipelines/audioldm2/modeling_audioldm2.py +1 -1
- diffusers/pipelines/audioldm2/pipeline_audioldm2.py +23 -13
- diffusers/pipelines/aura_flow/pipeline_aura_flow.py +48 -11
- diffusers/pipelines/auto_pipeline.py +6 -7
- diffusers/pipelines/blip_diffusion/modeling_blip2.py +1 -1
- diffusers/pipelines/blip_diffusion/modeling_ctx_clip.py +2 -2
- diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +11 -10
- diffusers/pipelines/chroma/__init__.py +49 -0
- diffusers/pipelines/chroma/pipeline_chroma.py +949 -0
- diffusers/pipelines/chroma/pipeline_chroma_img2img.py +1034 -0
- diffusers/pipelines/chroma/pipeline_output.py +21 -0
- diffusers/pipelines/cogvideo/pipeline_cogvideox.py +8 -8
- diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +8 -8
- diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +8 -8
- diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +8 -8
- diffusers/pipelines/cogview3/pipeline_cogview3plus.py +9 -9
- diffusers/pipelines/cogview4/pipeline_cogview4.py +7 -7
- diffusers/pipelines/cogview4/pipeline_cogview4_control.py +7 -7
- diffusers/pipelines/consisid/consisid_utils.py +2 -2
- diffusers/pipelines/consisid/pipeline_consisid.py +8 -8
- diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -1
- diffusers/pipelines/controlnet/pipeline_controlnet.py +7 -7
- diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +8 -8
- diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +7 -7
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +7 -7
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +14 -14
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +10 -6
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +13 -13
- diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +14 -14
- diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +5 -5
- diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +13 -13
- diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +1 -1
- diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +8 -8
- diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +7 -7
- diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +7 -7
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +12 -10
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +9 -7
- diffusers/pipelines/cosmos/__init__.py +54 -0
- diffusers/pipelines/cosmos/pipeline_cosmos2_text2image.py +673 -0
- diffusers/pipelines/cosmos/pipeline_cosmos2_video2world.py +792 -0
- diffusers/pipelines/cosmos/pipeline_cosmos_text2world.py +664 -0
- diffusers/pipelines/cosmos/pipeline_cosmos_video2world.py +826 -0
- diffusers/pipelines/cosmos/pipeline_output.py +40 -0
- diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +5 -4
- diffusers/pipelines/ddim/pipeline_ddim.py +4 -4
- diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if.py +10 -10
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +10 -10
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +10 -10
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +10 -10
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +10 -10
- diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +10 -10
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +8 -8
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +5 -5
- diffusers/pipelines/deprecated/audio_diffusion/mel.py +1 -1
- diffusers/pipelines/deprecated/audio_diffusion/pipeline_audio_diffusion.py +3 -3
- diffusers/pipelines/deprecated/latent_diffusion_uncond/pipeline_latent_diffusion_uncond.py +1 -1
- diffusers/pipelines/deprecated/pndm/pipeline_pndm.py +2 -2
- diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +4 -3
- diffusers/pipelines/deprecated/score_sde_ve/pipeline_score_sde_ve.py +1 -1
- diffusers/pipelines/deprecated/spectrogram_diffusion/continuous_encoder.py +1 -1
- diffusers/pipelines/deprecated/spectrogram_diffusion/midi_utils.py +1 -1
- diffusers/pipelines/deprecated/spectrogram_diffusion/notes_encoder.py +1 -1
- diffusers/pipelines/deprecated/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +1 -1
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +7 -7
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_onnx_stable_diffusion_inpaint_legacy.py +9 -9
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +10 -10
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +10 -8
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +5 -5
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +18 -18
- diffusers/pipelines/deprecated/stochastic_karras_ve/pipeline_stochastic_karras_ve.py +1 -1
- diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +2 -2
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py +6 -6
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +5 -5
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +5 -5
- diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +5 -5
- diffusers/pipelines/deprecated/vq_diffusion/pipeline_vq_diffusion.py +1 -1
- diffusers/pipelines/dit/pipeline_dit.py +1 -1
- diffusers/pipelines/easyanimate/pipeline_easyanimate.py +4 -4
- diffusers/pipelines/easyanimate/pipeline_easyanimate_control.py +4 -4
- diffusers/pipelines/easyanimate/pipeline_easyanimate_inpaint.py +7 -6
- diffusers/pipelines/flux/modeling_flux.py +1 -1
- diffusers/pipelines/flux/pipeline_flux.py +10 -17
- diffusers/pipelines/flux/pipeline_flux_control.py +6 -6
- diffusers/pipelines/flux/pipeline_flux_control_img2img.py +6 -6
- diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +6 -6
- diffusers/pipelines/flux/pipeline_flux_controlnet.py +6 -6
- diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +30 -22
- diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +2 -1
- diffusers/pipelines/flux/pipeline_flux_fill.py +6 -6
- diffusers/pipelines/flux/pipeline_flux_img2img.py +39 -6
- diffusers/pipelines/flux/pipeline_flux_inpaint.py +11 -6
- diffusers/pipelines/flux/pipeline_flux_prior_redux.py +1 -1
- diffusers/pipelines/free_init_utils.py +2 -2
- diffusers/pipelines/free_noise_utils.py +3 -3
- diffusers/pipelines/hidream_image/__init__.py +47 -0
- diffusers/pipelines/hidream_image/pipeline_hidream_image.py +1026 -0
- diffusers/pipelines/hidream_image/pipeline_output.py +35 -0
- diffusers/pipelines/hunyuan_video/__init__.py +2 -0
- diffusers/pipelines/hunyuan_video/pipeline_hunyuan_skyreels_image2video.py +8 -8
- diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +8 -8
- diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video_framepack.py +1114 -0
- diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video_image2video.py +71 -15
- diffusers/pipelines/hunyuan_video/pipeline_output.py +19 -0
- diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +8 -8
- diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +10 -8
- diffusers/pipelines/kandinsky/pipeline_kandinsky.py +6 -6
- diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +34 -34
- diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +19 -26
- diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +7 -7
- diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +11 -11
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +6 -6
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +35 -35
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +6 -6
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +17 -39
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +17 -45
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +7 -7
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +10 -10
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +10 -10
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +7 -7
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +17 -38
- diffusers/pipelines/kolors/pipeline_kolors.py +10 -10
- diffusers/pipelines/kolors/pipeline_kolors_img2img.py +12 -12
- diffusers/pipelines/kolors/text_encoder.py +3 -3
- diffusers/pipelines/kolors/tokenizer.py +1 -1
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +2 -2
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +2 -2
- diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -1
- diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion_superresolution.py +3 -3
- diffusers/pipelines/latte/pipeline_latte.py +12 -12
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +13 -13
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +17 -16
- diffusers/pipelines/ltx/__init__.py +4 -0
- diffusers/pipelines/ltx/modeling_latent_upsampler.py +188 -0
- diffusers/pipelines/ltx/pipeline_ltx.py +51 -6
- diffusers/pipelines/ltx/pipeline_ltx_condition.py +107 -29
- diffusers/pipelines/ltx/pipeline_ltx_image2video.py +50 -6
- diffusers/pipelines/ltx/pipeline_ltx_latent_upsample.py +277 -0
- diffusers/pipelines/lumina/pipeline_lumina.py +13 -13
- diffusers/pipelines/lumina2/pipeline_lumina2.py +10 -10
- diffusers/pipelines/marigold/marigold_image_processing.py +2 -2
- diffusers/pipelines/mochi/pipeline_mochi.py +6 -6
- diffusers/pipelines/musicldm/pipeline_musicldm.py +16 -13
- diffusers/pipelines/omnigen/pipeline_omnigen.py +13 -11
- diffusers/pipelines/omnigen/processor_omnigen.py +8 -3
- diffusers/pipelines/onnx_utils.py +15 -2
- diffusers/pipelines/pag/pag_utils.py +2 -2
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +12 -8
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +7 -7
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +10 -6
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +14 -14
- diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +8 -8
- diffusers/pipelines/pag/pipeline_pag_kolors.py +10 -10
- diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +11 -11
- diffusers/pipelines/pag/pipeline_pag_sana.py +18 -12
- diffusers/pipelines/pag/pipeline_pag_sd.py +8 -8
- diffusers/pipelines/pag/pipeline_pag_sd_3.py +7 -7
- diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +7 -7
- diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +6 -6
- diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +5 -5
- diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +8 -8
- diffusers/pipelines/pag/pipeline_pag_sd_xl.py +16 -15
- diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +18 -17
- diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +12 -12
- diffusers/pipelines/paint_by_example/image_encoder.py +1 -1
- diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +8 -7
- diffusers/pipelines/pia/pipeline_pia.py +8 -6
- diffusers/pipelines/pipeline_flax_utils.py +3 -4
- diffusers/pipelines/pipeline_loading_utils.py +89 -13
- diffusers/pipelines/pipeline_utils.py +105 -33
- diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +11 -11
- diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +11 -11
- diffusers/pipelines/sana/__init__.py +4 -0
- diffusers/pipelines/sana/pipeline_sana.py +23 -21
- diffusers/pipelines/sana/pipeline_sana_controlnet.py +1106 -0
- diffusers/pipelines/sana/pipeline_sana_sprint.py +23 -19
- diffusers/pipelines/sana/pipeline_sana_sprint_img2img.py +981 -0
- diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +7 -6
- diffusers/pipelines/shap_e/camera.py +1 -1
- diffusers/pipelines/shap_e/pipeline_shap_e.py +1 -1
- diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +1 -1
- diffusers/pipelines/shap_e/renderer.py +3 -3
- diffusers/pipelines/stable_audio/modeling_stable_audio.py +1 -1
- diffusers/pipelines/stable_audio/pipeline_stable_audio.py +5 -5
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +8 -8
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +13 -13
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +9 -9
- diffusers/pipelines/stable_diffusion/__init__.py +0 -7
- diffusers/pipelines/stable_diffusion/clip_image_project_model.py +1 -1
- diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +11 -4
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_img2img.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_inpaint.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +10 -10
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +10 -10
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +10 -10
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +9 -9
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +8 -8
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +5 -5
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +5 -5
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +5 -5
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +5 -5
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +5 -5
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +4 -4
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +5 -5
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +7 -7
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +5 -5
- diffusers/pipelines/stable_diffusion/safety_checker.py +1 -1
- diffusers/pipelines/stable_diffusion/safety_checker_flax.py +1 -1
- diffusers/pipelines/stable_diffusion/stable_unclip_image_normalizer.py +1 -1
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +7 -7
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +7 -7
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +7 -7
- diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +12 -8
- diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +15 -9
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +11 -9
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +11 -9
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +18 -12
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +11 -8
- diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +11 -8
- diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +15 -12
- diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +8 -6
- diffusers/pipelines/stable_diffusion_safe/safety_checker.py +1 -1
- diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +15 -11
- diffusers/pipelines/stable_diffusion_xl/pipeline_flax_stable_diffusion_xl.py +1 -1
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +16 -15
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +18 -17
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +12 -12
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +16 -15
- diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +3 -3
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +12 -12
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +18 -17
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +12 -7
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +12 -7
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +15 -13
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +24 -21
- diffusers/pipelines/unclip/pipeline_unclip.py +4 -3
- diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +4 -3
- diffusers/pipelines/unclip/text_proj.py +2 -2
- diffusers/pipelines/unidiffuser/modeling_text_decoder.py +2 -2
- diffusers/pipelines/unidiffuser/modeling_uvit.py +1 -1
- diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +8 -7
- diffusers/pipelines/visualcloze/__init__.py +52 -0
- diffusers/pipelines/visualcloze/pipeline_visualcloze_combined.py +444 -0
- diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py +952 -0
- diffusers/pipelines/visualcloze/visualcloze_utils.py +251 -0
- diffusers/pipelines/wan/__init__.py +2 -0
- diffusers/pipelines/wan/pipeline_wan.py +17 -12
- diffusers/pipelines/wan/pipeline_wan_i2v.py +42 -20
- diffusers/pipelines/wan/pipeline_wan_vace.py +976 -0
- diffusers/pipelines/wan/pipeline_wan_video2video.py +18 -18
- diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +1 -1
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py +1 -1
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +1 -1
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +8 -8
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +16 -15
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +6 -6
- diffusers/quantizers/__init__.py +179 -1
- diffusers/quantizers/base.py +6 -1
- diffusers/quantizers/bitsandbytes/bnb_quantizer.py +4 -0
- diffusers/quantizers/bitsandbytes/utils.py +10 -7
- diffusers/quantizers/gguf/gguf_quantizer.py +13 -4
- diffusers/quantizers/gguf/utils.py +16 -13
- diffusers/quantizers/quantization_config.py +18 -16
- diffusers/quantizers/quanto/quanto_quantizer.py +4 -0
- diffusers/quantizers/torchao/torchao_quantizer.py +5 -1
- diffusers/schedulers/__init__.py +3 -1
- diffusers/schedulers/deprecated/scheduling_karras_ve.py +4 -3
- diffusers/schedulers/deprecated/scheduling_sde_vp.py +1 -1
- diffusers/schedulers/scheduling_consistency_models.py +1 -1
- diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +10 -5
- diffusers/schedulers/scheduling_ddim.py +8 -8
- diffusers/schedulers/scheduling_ddim_cogvideox.py +5 -5
- diffusers/schedulers/scheduling_ddim_flax.py +6 -6
- diffusers/schedulers/scheduling_ddim_inverse.py +6 -6
- diffusers/schedulers/scheduling_ddim_parallel.py +22 -22
- diffusers/schedulers/scheduling_ddpm.py +9 -9
- diffusers/schedulers/scheduling_ddpm_flax.py +7 -7
- diffusers/schedulers/scheduling_ddpm_parallel.py +18 -18
- diffusers/schedulers/scheduling_ddpm_wuerstchen.py +2 -2
- diffusers/schedulers/scheduling_deis_multistep.py +8 -8
- diffusers/schedulers/scheduling_dpm_cogvideox.py +5 -5
- diffusers/schedulers/scheduling_dpmsolver_multistep.py +12 -12
- diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py +22 -20
- diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +11 -11
- diffusers/schedulers/scheduling_dpmsolver_sde.py +2 -2
- diffusers/schedulers/scheduling_dpmsolver_singlestep.py +13 -13
- diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +13 -8
- diffusers/schedulers/scheduling_edm_euler.py +20 -11
- diffusers/schedulers/scheduling_euler_ancestral_discrete.py +3 -3
- diffusers/schedulers/scheduling_euler_discrete.py +3 -3
- diffusers/schedulers/scheduling_euler_discrete_flax.py +3 -3
- diffusers/schedulers/scheduling_flow_match_euler_discrete.py +20 -5
- diffusers/schedulers/scheduling_flow_match_heun_discrete.py +1 -1
- diffusers/schedulers/scheduling_flow_match_lcm.py +561 -0
- diffusers/schedulers/scheduling_heun_discrete.py +2 -2
- diffusers/schedulers/scheduling_ipndm.py +2 -2
- diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +2 -2
- diffusers/schedulers/scheduling_k_dpm_2_discrete.py +2 -2
- diffusers/schedulers/scheduling_karras_ve_flax.py +5 -5
- diffusers/schedulers/scheduling_lcm.py +3 -3
- diffusers/schedulers/scheduling_lms_discrete.py +2 -2
- diffusers/schedulers/scheduling_lms_discrete_flax.py +1 -1
- diffusers/schedulers/scheduling_pndm.py +4 -4
- diffusers/schedulers/scheduling_pndm_flax.py +4 -4
- diffusers/schedulers/scheduling_repaint.py +9 -9
- diffusers/schedulers/scheduling_sasolver.py +15 -15
- diffusers/schedulers/scheduling_scm.py +1 -1
- diffusers/schedulers/scheduling_sde_ve.py +1 -1
- diffusers/schedulers/scheduling_sde_ve_flax.py +2 -2
- diffusers/schedulers/scheduling_tcd.py +3 -3
- diffusers/schedulers/scheduling_unclip.py +5 -5
- diffusers/schedulers/scheduling_unipc_multistep.py +11 -11
- diffusers/schedulers/scheduling_utils.py +1 -1
- diffusers/schedulers/scheduling_utils_flax.py +1 -1
- diffusers/schedulers/scheduling_vq_diffusion.py +1 -1
- diffusers/training_utils.py +13 -5
- diffusers/utils/__init__.py +5 -0
- diffusers/utils/accelerate_utils.py +1 -1
- diffusers/utils/doc_utils.py +1 -1
- diffusers/utils/dummy_pt_objects.py +120 -0
- diffusers/utils/dummy_torch_and_transformers_objects.py +225 -0
- diffusers/utils/dynamic_modules_utils.py +21 -3
- diffusers/utils/export_utils.py +1 -1
- diffusers/utils/import_utils.py +81 -18
- diffusers/utils/logging.py +1 -1
- diffusers/utils/outputs.py +2 -1
- diffusers/utils/peft_utils.py +91 -8
- diffusers/utils/state_dict_utils.py +20 -3
- diffusers/utils/testing_utils.py +59 -7
- diffusers/utils/torch_utils.py +25 -5
- diffusers/video_processor.py +2 -2
- {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/METADATA +3 -3
- diffusers-0.34.0.dist-info/RECORD +639 -0
- diffusers-0.33.0.dist-info/RECORD +0 -608
- {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/LICENSE +0 -0
- {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/WHEEL +0 -0
- {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/entry_points.txt +0 -0
- {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1108 @@
|
|
1
|
+
# Copyright 2025 The NVIDIA Team and The HuggingFace Team. All rights reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
|
15
|
+
import math
|
16
|
+
from typing import List, Optional, Tuple, Union
|
17
|
+
|
18
|
+
import torch
|
19
|
+
import torch.nn as nn
|
20
|
+
import torch.nn.functional as F
|
21
|
+
|
22
|
+
from ...configuration_utils import ConfigMixin, register_to_config
|
23
|
+
from ...utils import get_logger
|
24
|
+
from ...utils.accelerate_utils import apply_forward_hook
|
25
|
+
from ..modeling_outputs import AutoencoderKLOutput
|
26
|
+
from ..modeling_utils import ModelMixin
|
27
|
+
from .vae import DecoderOutput, IdentityDistribution
|
28
|
+
|
29
|
+
|
30
|
+
logger = get_logger(__name__)
|
31
|
+
|
32
|
+
|
33
|
+
# fmt: off
|
34
|
+
# These latents and means are from CV8x8x8-1.0. Each checkpoint has different values, but since this is the main VAE used,
|
35
|
+
# we will default to these values.
|
36
|
+
LATENTS_MEAN = [0.11362758, -0.0171717, 0.03071163, 0.02046862, 0.01931456, 0.02138567, 0.01999342, 0.02189187, 0.02011935, 0.01872694, 0.02168613, 0.02207148, 0.01986941, 0.01770413, 0.02067643, 0.02028245, 0.19125476, 0.04556972, 0.0595558, 0.05315534, 0.05496629, 0.05356264, 0.04856596, 0.05327453, 0.05410472, 0.05597149, 0.05524866, 0.05181874, 0.05071663, 0.05204537, 0.0564108, 0.05518042, 0.01306714, 0.03341161, 0.03847246, 0.02810185, 0.02790166, 0.02920026, 0.02823597, 0.02631033, 0.0278531, 0.02880507, 0.02977769, 0.03145441, 0.02888389, 0.03280773, 0.03484927, 0.03049198, -0.00197727, 0.07534957, 0.04963879, 0.05530893, 0.05410828, 0.05252541, 0.05029899, 0.05321025, 0.05149245, 0.0511921, 0.04643495, 0.04604527, 0.04631618, 0.04404101, 0.04403536, 0.04499495, -0.02994183, -0.04787003, -0.01064558, -0.01779824, -0.01490502, -0.02157517, -0.0204778, -0.02180816, -0.01945375, -0.02062863, -0.02192209, -0.02520639, -0.02246656, -0.02427533, -0.02683363, -0.02762006, 0.08019473, -0.13005368, -0.07568636, -0.06082374, -0.06036175, -0.05875364, -0.05921887, -0.05869788, -0.05273941, -0.052565, -0.05346428, -0.05456541, -0.053657, -0.05656897, -0.05728589, -0.05321847, 0.16718403, -0.00390146, 0.0379406, 0.0356561, 0.03554131, 0.03924074, 0.03873615, 0.04187329, 0.04226924, 0.04378717, 0.04684274, 0.05117614, 0.04547792, 0.05251586, 0.05048339, 0.04950784, 0.09564418, 0.0547128, 0.08183969, 0.07978633, 0.08076023, 0.08108605, 0.08011818, 0.07965573, 0.08187773, 0.08350263, 0.08101469, 0.0786941, 0.0774442, 0.07724521, 0.07830418, 0.07599796, -0.04987567, 0.05923908, -0.01058746, -0.01177603, -0.01116162, -0.01364149, -0.01546014, -0.0117213, -0.01780043, -0.01648314, -0.02100247, -0.02104417, -0.02482123, -0.02611689, -0.02561143, -0.02597336, -0.05364667, 0.08211684, 0.04686937, 0.04605641, 0.04304186, 0.0397355, 0.03686767, 0.04087112, 0.03704741, 0.03706401, 0.03120073, 0.03349091, 0.03319963, 0.03205781, 0.03195127, 0.03180481, 0.16427967, -0.11048453, -0.04595276, -0.04982893, -0.05213465, -0.04809378, -0.05080318, -0.04992863, -0.04493337, -0.0467619, -0.04884703, -0.04627892, -0.04913311, -0.04955709, -0.04533982, -0.04570218, -0.10612928, -0.05121198, -0.06761009, -0.07251801, -0.07265285, -0.07417855, -0.07202412, -0.07499027, -0.07625481, -0.07535747, -0.07638787, -0.07920305, -0.07596069, -0.07959418, -0.08265036, -0.07955471, -0.16888915, 0.0753242, 0.04062594, 0.03375093, 0.03337452, 0.03699376, 0.03651138, 0.03611023, 0.03555622, 0.03378554, 0.0300498, 0.03395559, 0.02941847, 0.03156432, 0.03431173, 0.03016853, -0.03415358, -0.01699573, -0.04029295, -0.04912157, -0.0498858, -0.04917918, -0.04918056, -0.0525189, -0.05325506, -0.05341973, -0.04983329, -0.04883146, -0.04985548, -0.04736718, -0.0462027, -0.04836091, 0.02055675, 0.03419799, -0.02907669, -0.04350509, -0.04156144, -0.04234421, -0.04446109, -0.04461774, -0.04882839, -0.04822346, -0.04502493, -0.0506244, -0.05146913, -0.04655267, -0.04862994, -0.04841615, 0.20312774, -0.07208502, -0.03635615, -0.03556088, -0.04246174, -0.04195838, -0.04293778, -0.04071276, -0.04240569, -0.04125213, -0.04395144, -0.03959096, -0.04044993, -0.04015875, -0.04088107, -0.03885176]
|
37
|
+
LATENTS_STD = [0.56700271, 0.65488982, 0.65589428, 0.66524369, 0.66619784, 0.6666382, 0.6720838, 0.66955978, 0.66928875, 0.67108786, 0.67092526, 0.67397463, 0.67894882, 0.67668313, 0.67769569, 0.67479557, 0.85245121, 0.8688373, 0.87348086, 0.88459337, 0.89135885, 0.8910504, 0.89714909, 0.89947474, 0.90201765, 0.90411824, 0.90692616, 0.90847772, 0.90648711, 0.91006982, 0.91033435, 0.90541548, 0.84960359, 0.85863352, 0.86895317, 0.88460612, 0.89245003, 0.89451706, 0.89931005, 0.90647358, 0.90338236, 0.90510076, 0.91008312, 0.90961218, 0.9123717, 0.91313171, 0.91435546, 0.91565102, 0.91877103, 0.85155135, 0.857804, 0.86998034, 0.87365264, 0.88161767, 0.88151032, 0.88758916, 0.89015514, 0.89245576, 0.89276224, 0.89450496, 0.90054202, 0.89994133, 0.90136105, 0.90114892, 0.77755755, 0.81456852, 0.81911844, 0.83137071, 0.83820474, 0.83890373, 0.84401101, 0.84425181, 0.84739357, 0.84798753, 0.85249585, 0.85114998, 0.85160935, 0.85626358, 0.85677862, 0.85641026, 0.69903517, 0.71697885, 0.71696913, 0.72583169, 0.72931731, 0.73254126, 0.73586977, 0.73734969, 0.73664582, 0.74084908, 0.74399322, 0.74471819, 0.74493188, 0.74824578, 0.75024873, 0.75274801, 0.8187142, 0.82251883, 0.82616025, 0.83164483, 0.84072375, 0.8396467, 0.84143305, 0.84880769, 0.8503468, 0.85196948, 0.85211051, 0.85386664, 0.85410017, 0.85439342, 0.85847849, 0.85385275, 0.67583984, 0.68259847, 0.69198853, 0.69928843, 0.70194328, 0.70467001, 0.70755547, 0.70917857, 0.71007699, 0.70963502, 0.71064079, 0.71027333, 0.71291167, 0.71537536, 0.71902508, 0.71604162, 0.72450989, 0.71979928, 0.72057378, 0.73035461, 0.73329622, 0.73660028, 0.73891461, 0.74279994, 0.74105692, 0.74002433, 0.74257588, 0.74416119, 0.74543899, 0.74694443, 0.74747062, 0.74586403, 0.90176988, 0.90990674, 0.91106802, 0.92163783, 0.92390233, 0.93056196, 0.93482202, 0.93642414, 0.93858379, 0.94064975, 0.94078934, 0.94325715, 0.94955301, 0.94814706, 0.95144123, 0.94923073, 0.49853548, 0.64968109, 0.6427654, 0.64966393, 0.6487664, 0.65203559, 0.6584242, 0.65351611, 0.65464371, 0.6574859, 0.65626335, 0.66123748, 0.66121179, 0.66077942, 0.66040152, 0.66474909, 0.61986589, 0.69138134, 0.6884557, 0.6955843, 0.69765401, 0.70015347, 0.70529598, 0.70468754, 0.70399523, 0.70479989, 0.70887572, 0.71126866, 0.7097227, 0.71249932, 0.71231949, 0.71175605, 0.35586974, 0.68723857, 0.68973219, 0.69958478, 0.6943453, 0.6995818, 0.70980215, 0.69899458, 0.70271689, 0.70095056, 0.69912851, 0.70522696, 0.70392174, 0.70916915, 0.70585734, 0.70373541, 0.98101336, 0.89024764, 0.89607251, 0.90678179, 0.91308665, 0.91812348, 0.91980827, 0.92480654, 0.92635667, 0.92887944, 0.93338072, 0.93468094, 0.93619436, 0.93906063, 0.94191772, 0.94471723, 0.83202779, 0.84106231, 0.84463632, 0.85829508, 0.86319661, 0.86751342, 0.86914337, 0.87085921, 0.87286359, 0.87537396, 0.87931138, 0.88054478, 0.8811838, 0.88872558, 0.88942474, 0.88934827, 0.44025335, 0.63061613, 0.63110614, 0.63601959, 0.6395812, 0.64104342, 0.65019929, 0.6502797, 0.64355946, 0.64657205, 0.64847094, 0.64728117, 0.64972943, 0.65162975, 0.65328044, 0.64914775]
|
38
|
+
_WAVELETS = {
|
39
|
+
"haar": torch.tensor([0.7071067811865476, 0.7071067811865476]),
|
40
|
+
"rearrange": torch.tensor([1.0, 1.0]),
|
41
|
+
}
|
42
|
+
# fmt: on
|
43
|
+
|
44
|
+
|
45
|
+
class CosmosCausalConv3d(nn.Conv3d):
|
46
|
+
def __init__(
|
47
|
+
self,
|
48
|
+
in_channels: int = 1,
|
49
|
+
out_channels: int = 1,
|
50
|
+
kernel_size: Union[int, Tuple[int, int, int]] = (3, 3, 3),
|
51
|
+
dilation: Union[int, Tuple[int, int, int]] = (1, 1, 1),
|
52
|
+
stride: Union[int, Tuple[int, int, int]] = (1, 1, 1),
|
53
|
+
padding: int = 1,
|
54
|
+
pad_mode: str = "constant",
|
55
|
+
) -> None:
|
56
|
+
kernel_size = (kernel_size, kernel_size, kernel_size) if isinstance(kernel_size, int) else kernel_size
|
57
|
+
dilation = (dilation, dilation, dilation) if isinstance(dilation, int) else dilation
|
58
|
+
stride = (stride, stride, stride) if isinstance(stride, int) else stride
|
59
|
+
|
60
|
+
_, height_kernel_size, width_kernel_size = kernel_size
|
61
|
+
assert height_kernel_size % 2 == 1 and width_kernel_size % 2 == 1
|
62
|
+
|
63
|
+
super().__init__(
|
64
|
+
in_channels,
|
65
|
+
out_channels,
|
66
|
+
kernel_size,
|
67
|
+
stride=stride,
|
68
|
+
dilation=dilation,
|
69
|
+
)
|
70
|
+
|
71
|
+
self.pad_mode = pad_mode
|
72
|
+
self.temporal_pad = dilation[0] * (kernel_size[0] - 1) + (1 - stride[0])
|
73
|
+
self.spatial_pad = (padding, padding, padding, padding)
|
74
|
+
|
75
|
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
76
|
+
hidden_states_prev = hidden_states[:, :, :1, ...].repeat(1, 1, self.temporal_pad, 1, 1)
|
77
|
+
hidden_states = torch.cat([hidden_states_prev, hidden_states], dim=2)
|
78
|
+
hidden_states = F.pad(hidden_states, (*self.spatial_pad, 0, 0), mode=self.pad_mode, value=0.0)
|
79
|
+
return super().forward(hidden_states)
|
80
|
+
|
81
|
+
|
82
|
+
class CosmosCausalGroupNorm(torch.nn.Module):
|
83
|
+
def __init__(self, in_channels: int, num_groups: int = 1):
|
84
|
+
super().__init__()
|
85
|
+
self.norm = nn.GroupNorm(
|
86
|
+
num_groups=num_groups,
|
87
|
+
num_channels=in_channels,
|
88
|
+
eps=1e-6,
|
89
|
+
affine=True,
|
90
|
+
)
|
91
|
+
self.num_groups = num_groups
|
92
|
+
|
93
|
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
94
|
+
if self.num_groups == 1:
|
95
|
+
batch_size = hidden_states.size(0)
|
96
|
+
hidden_states = hidden_states.permute(0, 2, 1, 3, 4).flatten(0, 1) # [B, C, T, H, W] -> [B * T, C, H, W]
|
97
|
+
hidden_states = self.norm(hidden_states)
|
98
|
+
hidden_states = hidden_states.unflatten(0, (batch_size, -1)).permute(
|
99
|
+
0, 2, 1, 3, 4
|
100
|
+
) # [B * T, C, H, W] -> [B, C, T, H, W]
|
101
|
+
else:
|
102
|
+
hidden_states = self.norm(hidden_states)
|
103
|
+
return hidden_states
|
104
|
+
|
105
|
+
|
106
|
+
class CosmosPatchEmbed3d(nn.Module):
|
107
|
+
def __init__(self, patch_size: int = 1, patch_method: str = "haar") -> None:
|
108
|
+
super().__init__()
|
109
|
+
|
110
|
+
self.patch_size = patch_size
|
111
|
+
self.patch_method = patch_method
|
112
|
+
|
113
|
+
wavelets = _WAVELETS.get(patch_method).clone()
|
114
|
+
arange = torch.arange(wavelets.shape[0])
|
115
|
+
|
116
|
+
self.register_buffer("wavelets", wavelets, persistent=False)
|
117
|
+
self.register_buffer("_arange", arange, persistent=False)
|
118
|
+
|
119
|
+
def _dwt(self, hidden_states: torch.Tensor, mode: str = "reflect", rescale=False) -> torch.Tensor:
|
120
|
+
dtype = hidden_states.dtype
|
121
|
+
wavelets = self.wavelets
|
122
|
+
|
123
|
+
n = wavelets.shape[0]
|
124
|
+
g = hidden_states.shape[1]
|
125
|
+
hl = wavelets.flip(0).reshape(1, 1, -1).repeat(g, 1, 1)
|
126
|
+
hh = (wavelets * ((-1) ** self._arange)).reshape(1, 1, -1).repeat(g, 1, 1)
|
127
|
+
hh = hh.to(dtype=dtype)
|
128
|
+
hl = hl.to(dtype=dtype)
|
129
|
+
|
130
|
+
# Handles temporal axis
|
131
|
+
hidden_states = F.pad(hidden_states, pad=(max(0, n - 2), n - 1, n - 2, n - 1, n - 2, n - 1), mode=mode).to(
|
132
|
+
dtype
|
133
|
+
)
|
134
|
+
xl = F.conv3d(hidden_states, hl.unsqueeze(3).unsqueeze(4), groups=g, stride=(2, 1, 1))
|
135
|
+
xh = F.conv3d(hidden_states, hh.unsqueeze(3).unsqueeze(4), groups=g, stride=(2, 1, 1))
|
136
|
+
|
137
|
+
# Handles spatial axes
|
138
|
+
xll = F.conv3d(xl, hl.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1))
|
139
|
+
xlh = F.conv3d(xl, hh.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1))
|
140
|
+
xhl = F.conv3d(xh, hl.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1))
|
141
|
+
xhh = F.conv3d(xh, hh.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1))
|
142
|
+
|
143
|
+
xlll = F.conv3d(xll, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
|
144
|
+
xllh = F.conv3d(xll, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
|
145
|
+
xlhl = F.conv3d(xlh, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
|
146
|
+
xlhh = F.conv3d(xlh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
|
147
|
+
xhll = F.conv3d(xhl, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
|
148
|
+
xhlh = F.conv3d(xhl, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
|
149
|
+
xhhl = F.conv3d(xhh, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
|
150
|
+
xhhh = F.conv3d(xhh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
|
151
|
+
|
152
|
+
hidden_states = torch.cat([xlll, xllh, xlhl, xlhh, xhll, xhlh, xhhl, xhhh], dim=1)
|
153
|
+
if rescale:
|
154
|
+
hidden_states = hidden_states / 8**0.5
|
155
|
+
return hidden_states
|
156
|
+
|
157
|
+
def _haar(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
158
|
+
xi, xv = torch.split(hidden_states, [1, hidden_states.shape[2] - 1], dim=2)
|
159
|
+
hidden_states = torch.cat([xi.repeat_interleave(self.patch_size, dim=2), xv], dim=2)
|
160
|
+
for _ in range(int(math.log2(self.patch_size))):
|
161
|
+
hidden_states = self._dwt(hidden_states, rescale=True)
|
162
|
+
return hidden_states
|
163
|
+
|
164
|
+
def _arrange(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
165
|
+
xi, xv = torch.split(hidden_states, [1, hidden_states.shape[2] - 1], dim=2)
|
166
|
+
hidden_states = torch.cat([xi.repeat_interleave(self.patch_size, dim=2), xv], dim=2)
|
167
|
+
|
168
|
+
batch_size, num_channels, num_frames, height, width = hidden_states.shape
|
169
|
+
p = self.patch_size
|
170
|
+
|
171
|
+
hidden_states = torch.reshape(batch_size, num_channels, num_frames // p, p, height // p, p, width // p, p)
|
172
|
+
hidden_states = hidden_states.permute(0, 1, 3, 5, 7, 2, 4, 6).flatten(1, 4).contiguous()
|
173
|
+
return hidden_states
|
174
|
+
|
175
|
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
176
|
+
if self.patch_method == "haar":
|
177
|
+
return self._haar(hidden_states)
|
178
|
+
elif self.patch_method == "rearrange":
|
179
|
+
return self._arrange(hidden_states)
|
180
|
+
else:
|
181
|
+
raise ValueError(f"Unsupported patch method: {self.patch_method}")
|
182
|
+
|
183
|
+
|
184
|
+
class CosmosUnpatcher3d(nn.Module):
|
185
|
+
def __init__(self, patch_size: int = 1, patch_method: str = "haar"):
|
186
|
+
super().__init__()
|
187
|
+
|
188
|
+
self.patch_size = patch_size
|
189
|
+
self.patch_method = patch_method
|
190
|
+
|
191
|
+
wavelets = _WAVELETS.get(patch_method).clone()
|
192
|
+
arange = torch.arange(wavelets.shape[0])
|
193
|
+
|
194
|
+
self.register_buffer("wavelets", wavelets, persistent=False)
|
195
|
+
self.register_buffer("_arange", arange, persistent=False)
|
196
|
+
|
197
|
+
def _idwt(self, hidden_states: torch.Tensor, rescale: bool = False) -> torch.Tensor:
|
198
|
+
device = hidden_states.device
|
199
|
+
dtype = hidden_states.dtype
|
200
|
+
h = self.wavelets.to(device)
|
201
|
+
|
202
|
+
g = hidden_states.shape[1] // 8 # split into 8 spatio-temporal filtered tesnors.
|
203
|
+
hl = h.flip([0]).reshape(1, 1, -1).repeat([g, 1, 1])
|
204
|
+
hh = (h * ((-1) ** self._arange.to(device))).reshape(1, 1, -1).repeat(g, 1, 1)
|
205
|
+
hl = hl.to(dtype=dtype)
|
206
|
+
hh = hh.to(dtype=dtype)
|
207
|
+
|
208
|
+
xlll, xllh, xlhl, xlhh, xhll, xhlh, xhhl, xhhh = torch.chunk(hidden_states, 8, dim=1)
|
209
|
+
|
210
|
+
# Handle height transposed convolutions
|
211
|
+
xll = F.conv_transpose3d(xlll, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
|
212
|
+
xll = F.conv_transpose3d(xllh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xll
|
213
|
+
|
214
|
+
xlh = F.conv_transpose3d(xlhl, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
|
215
|
+
xlh = F.conv_transpose3d(xlhh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xlh
|
216
|
+
|
217
|
+
xhl = F.conv_transpose3d(xhll, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
|
218
|
+
xhl = F.conv_transpose3d(xhlh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xhl
|
219
|
+
|
220
|
+
xhh = F.conv_transpose3d(xhhl, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
|
221
|
+
xhh = F.conv_transpose3d(xhhh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xhh
|
222
|
+
|
223
|
+
# Handles width transposed convolutions
|
224
|
+
xl = F.conv_transpose3d(xll, hl.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1))
|
225
|
+
xl = F.conv_transpose3d(xlh, hh.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1)) + xl
|
226
|
+
xh = F.conv_transpose3d(xhl, hl.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1))
|
227
|
+
xh = F.conv_transpose3d(xhh, hh.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1)) + xh
|
228
|
+
|
229
|
+
# Handles time axis transposed convolutions
|
230
|
+
hidden_states = F.conv_transpose3d(xl, hl.unsqueeze(3).unsqueeze(4), groups=g, stride=(2, 1, 1))
|
231
|
+
hidden_states = (
|
232
|
+
F.conv_transpose3d(xh, hh.unsqueeze(3).unsqueeze(4), groups=g, stride=(2, 1, 1)) + hidden_states
|
233
|
+
)
|
234
|
+
|
235
|
+
if rescale:
|
236
|
+
hidden_states = hidden_states * 8**0.5
|
237
|
+
|
238
|
+
return hidden_states
|
239
|
+
|
240
|
+
def _ihaar(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
241
|
+
for _ in range(int(math.log2(self.patch_size))):
|
242
|
+
hidden_states = self._idwt(hidden_states, rescale=True)
|
243
|
+
hidden_states = hidden_states[:, :, self.patch_size - 1 :, ...]
|
244
|
+
return hidden_states
|
245
|
+
|
246
|
+
def _irearrange(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
247
|
+
p = self.patch_size
|
248
|
+
hidden_states = hidden_states.unflatten(1, (-1, p, p, p))
|
249
|
+
hidden_states = hidden_states.permute(0, 1, 5, 2, 6, 3, 7, 4)
|
250
|
+
hidden_states = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
|
251
|
+
hidden_states = hidden_states[:, :, p - 1 :, ...]
|
252
|
+
return hidden_states
|
253
|
+
|
254
|
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
255
|
+
if self.patch_method == "haar":
|
256
|
+
return self._ihaar(hidden_states)
|
257
|
+
elif self.patch_method == "rearrange":
|
258
|
+
return self._irearrange(hidden_states)
|
259
|
+
else:
|
260
|
+
raise ValueError("Unknown patch method: " + self.patch_method)
|
261
|
+
|
262
|
+
|
263
|
+
class CosmosConvProjection3d(nn.Module):
|
264
|
+
def __init__(self, in_channels: int, out_channels: int) -> None:
|
265
|
+
super().__init__()
|
266
|
+
|
267
|
+
self.conv_s = CosmosCausalConv3d(in_channels, out_channels, kernel_size=(1, 3, 3), stride=1, padding=1)
|
268
|
+
self.conv_t = CosmosCausalConv3d(out_channels, out_channels, kernel_size=(3, 1, 1), stride=1, padding=0)
|
269
|
+
|
270
|
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
271
|
+
hidden_states = self.conv_s(hidden_states)
|
272
|
+
hidden_states = self.conv_t(hidden_states)
|
273
|
+
return hidden_states
|
274
|
+
|
275
|
+
|
276
|
+
class CosmosResnetBlock3d(nn.Module):
|
277
|
+
def __init__(
|
278
|
+
self,
|
279
|
+
in_channels: int,
|
280
|
+
out_channels: int,
|
281
|
+
dropout: float = 0.0,
|
282
|
+
num_groups: int = 1,
|
283
|
+
) -> None:
|
284
|
+
super().__init__()
|
285
|
+
out_channels = out_channels or in_channels
|
286
|
+
|
287
|
+
self.norm1 = CosmosCausalGroupNorm(in_channels, num_groups)
|
288
|
+
self.conv1 = CosmosConvProjection3d(in_channels, out_channels)
|
289
|
+
|
290
|
+
self.norm2 = CosmosCausalGroupNorm(out_channels, num_groups)
|
291
|
+
self.dropout = nn.Dropout(dropout)
|
292
|
+
self.conv2 = CosmosConvProjection3d(out_channels, out_channels)
|
293
|
+
|
294
|
+
if in_channels != out_channels:
|
295
|
+
self.conv_shortcut = CosmosCausalConv3d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
|
296
|
+
else:
|
297
|
+
self.conv_shortcut = nn.Identity()
|
298
|
+
|
299
|
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
300
|
+
residual = hidden_states
|
301
|
+
residual = self.conv_shortcut(residual)
|
302
|
+
|
303
|
+
hidden_states = self.norm1(hidden_states)
|
304
|
+
hidden_states = F.silu(hidden_states)
|
305
|
+
hidden_states = self.conv1(hidden_states)
|
306
|
+
|
307
|
+
hidden_states = self.norm2(hidden_states)
|
308
|
+
hidden_states = F.silu(hidden_states)
|
309
|
+
hidden_states = self.dropout(hidden_states)
|
310
|
+
hidden_states = self.conv2(hidden_states)
|
311
|
+
|
312
|
+
return hidden_states + residual
|
313
|
+
|
314
|
+
|
315
|
+
class CosmosDownsample3d(nn.Module):
|
316
|
+
def __init__(
|
317
|
+
self,
|
318
|
+
in_channels: int,
|
319
|
+
spatial_downsample: bool = True,
|
320
|
+
temporal_downsample: bool = True,
|
321
|
+
) -> None:
|
322
|
+
super().__init__()
|
323
|
+
|
324
|
+
self.spatial_downsample = spatial_downsample
|
325
|
+
self.temporal_downsample = temporal_downsample
|
326
|
+
|
327
|
+
self.conv1 = nn.Identity()
|
328
|
+
self.conv2 = nn.Identity()
|
329
|
+
self.conv3 = nn.Identity()
|
330
|
+
|
331
|
+
if spatial_downsample:
|
332
|
+
self.conv1 = CosmosCausalConv3d(
|
333
|
+
in_channels, in_channels, kernel_size=(1, 3, 3), stride=(1, 2, 2), padding=0
|
334
|
+
)
|
335
|
+
if temporal_downsample:
|
336
|
+
self.conv2 = CosmosCausalConv3d(
|
337
|
+
in_channels, in_channels, kernel_size=(3, 1, 1), stride=(2, 1, 1), padding=0
|
338
|
+
)
|
339
|
+
if spatial_downsample or temporal_downsample:
|
340
|
+
self.conv3 = CosmosCausalConv3d(
|
341
|
+
in_channels, in_channels, kernel_size=(1, 1, 1), stride=(1, 1, 1), padding=0
|
342
|
+
)
|
343
|
+
|
344
|
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
345
|
+
if not self.spatial_downsample and not self.temporal_downsample:
|
346
|
+
return hidden_states
|
347
|
+
|
348
|
+
if self.spatial_downsample:
|
349
|
+
pad = (0, 1, 0, 1, 0, 0)
|
350
|
+
hidden_states = F.pad(hidden_states, pad, mode="constant", value=0)
|
351
|
+
conv_out = self.conv1(hidden_states)
|
352
|
+
pool_out = F.avg_pool3d(hidden_states, kernel_size=(1, 2, 2), stride=(1, 2, 2))
|
353
|
+
hidden_states = conv_out + pool_out
|
354
|
+
|
355
|
+
if self.temporal_downsample:
|
356
|
+
hidden_states = torch.cat([hidden_states[:, :, :1, ...], hidden_states], dim=2)
|
357
|
+
conv_out = self.conv2(hidden_states)
|
358
|
+
pool_out = F.avg_pool3d(hidden_states, kernel_size=(2, 1, 1), stride=(2, 1, 1))
|
359
|
+
hidden_states = conv_out + pool_out
|
360
|
+
|
361
|
+
hidden_states = self.conv3(hidden_states)
|
362
|
+
return hidden_states
|
363
|
+
|
364
|
+
|
365
|
+
class CosmosUpsample3d(nn.Module):
|
366
|
+
def __init__(
|
367
|
+
self,
|
368
|
+
in_channels: int,
|
369
|
+
spatial_upsample: bool = True,
|
370
|
+
temporal_upsample: bool = True,
|
371
|
+
) -> None:
|
372
|
+
super().__init__()
|
373
|
+
|
374
|
+
self.spatial_upsample = spatial_upsample
|
375
|
+
self.temporal_upsample = temporal_upsample
|
376
|
+
|
377
|
+
self.conv1 = nn.Identity()
|
378
|
+
self.conv2 = nn.Identity()
|
379
|
+
self.conv3 = nn.Identity()
|
380
|
+
|
381
|
+
if temporal_upsample:
|
382
|
+
self.conv1 = CosmosCausalConv3d(
|
383
|
+
in_channels, in_channels, kernel_size=(3, 1, 1), stride=(1, 1, 1), padding=0
|
384
|
+
)
|
385
|
+
if spatial_upsample:
|
386
|
+
self.conv2 = CosmosCausalConv3d(
|
387
|
+
in_channels, in_channels, kernel_size=(1, 3, 3), stride=(1, 1, 1), padding=1
|
388
|
+
)
|
389
|
+
if spatial_upsample or temporal_upsample:
|
390
|
+
self.conv3 = CosmosCausalConv3d(
|
391
|
+
in_channels, in_channels, kernel_size=(1, 1, 1), stride=(1, 1, 1), padding=0
|
392
|
+
)
|
393
|
+
|
394
|
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
395
|
+
if not self.spatial_upsample and not self.temporal_upsample:
|
396
|
+
return hidden_states
|
397
|
+
|
398
|
+
if self.temporal_upsample:
|
399
|
+
num_frames = hidden_states.size(2)
|
400
|
+
time_factor = int(1.0 + 1.0 * (num_frames > 1))
|
401
|
+
hidden_states = hidden_states.repeat_interleave(int(time_factor), dim=2)
|
402
|
+
hidden_states = hidden_states[..., time_factor - 1 :, :, :]
|
403
|
+
hidden_states = self.conv1(hidden_states) + hidden_states
|
404
|
+
|
405
|
+
if self.spatial_upsample:
|
406
|
+
hidden_states = hidden_states.repeat_interleave(2, dim=3).repeat_interleave(2, dim=4)
|
407
|
+
hidden_states = self.conv2(hidden_states) + hidden_states
|
408
|
+
|
409
|
+
hidden_states = self.conv3(hidden_states)
|
410
|
+
return hidden_states
|
411
|
+
|
412
|
+
|
413
|
+
class CosmosCausalAttention(nn.Module):
|
414
|
+
def __init__(
|
415
|
+
self,
|
416
|
+
num_attention_heads: int,
|
417
|
+
attention_head_dim: int,
|
418
|
+
num_groups: int = 1,
|
419
|
+
dropout: float = 0.0,
|
420
|
+
processor: Union["CosmosSpatialAttentionProcessor2_0", "CosmosTemporalAttentionProcessor2_0"] = None,
|
421
|
+
) -> None:
|
422
|
+
super().__init__()
|
423
|
+
self.num_attention_heads = num_attention_heads
|
424
|
+
|
425
|
+
self.norm = CosmosCausalGroupNorm(attention_head_dim, num_groups=num_groups)
|
426
|
+
self.to_q = CosmosCausalConv3d(attention_head_dim, attention_head_dim, kernel_size=1, stride=1, padding=0)
|
427
|
+
self.to_k = CosmosCausalConv3d(attention_head_dim, attention_head_dim, kernel_size=1, stride=1, padding=0)
|
428
|
+
self.to_v = CosmosCausalConv3d(attention_head_dim, attention_head_dim, kernel_size=1, stride=1, padding=0)
|
429
|
+
self.to_out = nn.ModuleList([])
|
430
|
+
self.to_out.append(
|
431
|
+
CosmosCausalConv3d(attention_head_dim, attention_head_dim, kernel_size=1, stride=1, padding=0)
|
432
|
+
)
|
433
|
+
self.to_out.append(nn.Dropout(dropout))
|
434
|
+
|
435
|
+
self.processor = processor
|
436
|
+
if self.processor is None:
|
437
|
+
raise ValueError("CosmosCausalAttention requires a processor.")
|
438
|
+
|
439
|
+
def forward(self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
|
440
|
+
return self.processor(self, hidden_states=hidden_states, attention_mask=attention_mask)
|
441
|
+
|
442
|
+
|
443
|
+
class CosmosSpatialAttentionProcessor2_0:
|
444
|
+
def __init__(self):
|
445
|
+
if not hasattr(F, "scaled_dot_product_attention"):
|
446
|
+
raise ImportError(
|
447
|
+
"CosmosSpatialAttentionProcessor2_0 requires PyTorch 2.0 or higher. To use it, please upgrade PyTorch."
|
448
|
+
)
|
449
|
+
|
450
|
+
def __call__(
|
451
|
+
self, attn: CosmosCausalAttention, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None
|
452
|
+
) -> torch.Tensor:
|
453
|
+
batch_size, num_channels, num_frames, height, width = hidden_states.shape
|
454
|
+
residual = hidden_states
|
455
|
+
|
456
|
+
hidden_states = attn.norm(hidden_states)
|
457
|
+
query = attn.to_q(hidden_states)
|
458
|
+
key = attn.to_k(hidden_states)
|
459
|
+
value = attn.to_v(hidden_states)
|
460
|
+
|
461
|
+
# [B, C, T, H, W] -> [B * T, H * W, C]
|
462
|
+
query = query.permute(0, 2, 3, 4, 1).flatten(2, 3).flatten(0, 1)
|
463
|
+
key = key.permute(0, 2, 3, 4, 1).flatten(2, 3).flatten(0, 1)
|
464
|
+
value = value.permute(0, 2, 3, 4, 1).flatten(2, 3).flatten(0, 1)
|
465
|
+
|
466
|
+
# [B * T, H * W, C] -> [B * T, N, H * W, C // N]
|
467
|
+
query = query.unflatten(2, (attn.num_attention_heads, -1)).transpose(1, 2)
|
468
|
+
key = key.unflatten(2, (attn.num_attention_heads, -1)).transpose(1, 2)
|
469
|
+
value = value.unflatten(2, (attn.num_attention_heads, -1)).transpose(1, 2)
|
470
|
+
|
471
|
+
hidden_states = F.scaled_dot_product_attention(query, key, value, attn_mask=attention_mask)
|
472
|
+
hidden_states = hidden_states.transpose(1, 2).flatten(2, 3).type_as(query)
|
473
|
+
hidden_states = hidden_states.unflatten(1, (height, width)).unflatten(0, (batch_size, num_frames))
|
474
|
+
hidden_states = hidden_states.permute(0, 4, 1, 2, 3)
|
475
|
+
|
476
|
+
hidden_states = attn.to_out[0](hidden_states)
|
477
|
+
hidden_states = attn.to_out[1](hidden_states)
|
478
|
+
|
479
|
+
return hidden_states + residual
|
480
|
+
|
481
|
+
|
482
|
+
class CosmosTemporalAttentionProcessor2_0:
|
483
|
+
def __init__(self):
|
484
|
+
if not hasattr(F, "scaled_dot_product_attention"):
|
485
|
+
raise ImportError(
|
486
|
+
"CosmosSpatialAttentionProcessor2_0 requires PyTorch 2.0 or higher. To use it, please upgrade PyTorch."
|
487
|
+
)
|
488
|
+
|
489
|
+
def __call__(
|
490
|
+
self, attn: CosmosCausalAttention, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None
|
491
|
+
) -> torch.Tensor:
|
492
|
+
batch_size, num_channels, num_frames, height, width = hidden_states.shape
|
493
|
+
residual = hidden_states
|
494
|
+
|
495
|
+
hidden_states = attn.norm(hidden_states)
|
496
|
+
query = attn.to_q(hidden_states)
|
497
|
+
key = attn.to_k(hidden_states)
|
498
|
+
value = attn.to_v(hidden_states)
|
499
|
+
|
500
|
+
# [B, C, T, H, W] -> [B * T, H * W, C]
|
501
|
+
query = query.permute(0, 3, 4, 2, 1).flatten(0, 2)
|
502
|
+
key = key.permute(0, 3, 4, 2, 1).flatten(0, 2)
|
503
|
+
value = value.permute(0, 3, 4, 2, 1).flatten(0, 2)
|
504
|
+
|
505
|
+
# [B * T, H * W, C] -> [B * T, N, H * W, C // N]
|
506
|
+
query = query.unflatten(2, (attn.num_attention_heads, -1)).transpose(1, 2)
|
507
|
+
key = key.unflatten(2, (attn.num_attention_heads, -1)).transpose(1, 2)
|
508
|
+
value = value.unflatten(2, (attn.num_attention_heads, -1)).transpose(1, 2)
|
509
|
+
|
510
|
+
hidden_states = F.scaled_dot_product_attention(query, key, value, attn_mask=attention_mask)
|
511
|
+
hidden_states = hidden_states.transpose(1, 2).flatten(2, 3).type_as(query)
|
512
|
+
hidden_states = hidden_states.unflatten(0, (batch_size, height, width))
|
513
|
+
hidden_states = hidden_states.permute(0, 4, 3, 1, 2)
|
514
|
+
|
515
|
+
hidden_states = attn.to_out[0](hidden_states)
|
516
|
+
hidden_states = attn.to_out[1](hidden_states)
|
517
|
+
|
518
|
+
return hidden_states + residual
|
519
|
+
|
520
|
+
|
521
|
+
class CosmosDownBlock3d(nn.Module):
|
522
|
+
def __init__(
|
523
|
+
self,
|
524
|
+
in_channels: int,
|
525
|
+
out_channels: int,
|
526
|
+
num_layers: int,
|
527
|
+
dropout: float,
|
528
|
+
use_attention: bool,
|
529
|
+
use_downsample: bool,
|
530
|
+
spatial_downsample: bool,
|
531
|
+
temporal_downsample: bool,
|
532
|
+
) -> None:
|
533
|
+
super().__init__()
|
534
|
+
|
535
|
+
resnets, attentions, temp_attentions = [], [], []
|
536
|
+
in_channel, out_channel = in_channels, out_channels
|
537
|
+
|
538
|
+
for _ in range(num_layers):
|
539
|
+
resnets.append(CosmosResnetBlock3d(in_channel, out_channel, dropout, num_groups=1))
|
540
|
+
in_channel = out_channel
|
541
|
+
|
542
|
+
if use_attention:
|
543
|
+
attentions.append(
|
544
|
+
CosmosCausalAttention(
|
545
|
+
num_attention_heads=1,
|
546
|
+
attention_head_dim=out_channel,
|
547
|
+
num_groups=1,
|
548
|
+
dropout=dropout,
|
549
|
+
processor=CosmosSpatialAttentionProcessor2_0(),
|
550
|
+
)
|
551
|
+
)
|
552
|
+
temp_attentions.append(
|
553
|
+
CosmosCausalAttention(
|
554
|
+
num_attention_heads=1,
|
555
|
+
attention_head_dim=out_channel,
|
556
|
+
num_groups=1,
|
557
|
+
dropout=dropout,
|
558
|
+
processor=CosmosTemporalAttentionProcessor2_0(),
|
559
|
+
)
|
560
|
+
)
|
561
|
+
else:
|
562
|
+
attentions.append(None)
|
563
|
+
temp_attentions.append(None)
|
564
|
+
|
565
|
+
self.resnets = nn.ModuleList(resnets)
|
566
|
+
self.attentions = nn.ModuleList(attentions)
|
567
|
+
self.temp_attentions = nn.ModuleList(temp_attentions)
|
568
|
+
|
569
|
+
self.downsamplers = None
|
570
|
+
if use_downsample:
|
571
|
+
self.downsamplers = nn.ModuleList([])
|
572
|
+
self.downsamplers.append(CosmosDownsample3d(out_channel, spatial_downsample, temporal_downsample))
|
573
|
+
|
574
|
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
575
|
+
for resnet, attention, temp_attention in zip(self.resnets, self.attentions, self.temp_attentions):
|
576
|
+
hidden_states = resnet(hidden_states)
|
577
|
+
if attention is not None:
|
578
|
+
hidden_states = attention(hidden_states)
|
579
|
+
if temp_attention is not None:
|
580
|
+
num_frames = hidden_states.size(2)
|
581
|
+
attention_mask = torch.tril(hidden_states.new_ones(num_frames, num_frames)).bool()
|
582
|
+
hidden_states = temp_attention(hidden_states, attention_mask)
|
583
|
+
|
584
|
+
if self.downsamplers is not None:
|
585
|
+
for downsampler in self.downsamplers:
|
586
|
+
hidden_states = downsampler(hidden_states)
|
587
|
+
|
588
|
+
return hidden_states
|
589
|
+
|
590
|
+
|
591
|
+
class CosmosMidBlock3d(nn.Module):
|
592
|
+
def __init__(self, in_channels: int, num_layers: int, dropout: float, num_groups: int = 1) -> None:
|
593
|
+
super().__init__()
|
594
|
+
|
595
|
+
resnets, attentions, temp_attentions = [], [], []
|
596
|
+
|
597
|
+
resnets.append(CosmosResnetBlock3d(in_channels, in_channels, dropout, num_groups))
|
598
|
+
for _ in range(num_layers):
|
599
|
+
attentions.append(
|
600
|
+
CosmosCausalAttention(
|
601
|
+
num_attention_heads=1,
|
602
|
+
attention_head_dim=in_channels,
|
603
|
+
num_groups=num_groups,
|
604
|
+
dropout=dropout,
|
605
|
+
processor=CosmosSpatialAttentionProcessor2_0(),
|
606
|
+
)
|
607
|
+
)
|
608
|
+
temp_attentions.append(
|
609
|
+
CosmosCausalAttention(
|
610
|
+
num_attention_heads=1,
|
611
|
+
attention_head_dim=in_channels,
|
612
|
+
num_groups=num_groups,
|
613
|
+
dropout=dropout,
|
614
|
+
processor=CosmosTemporalAttentionProcessor2_0(),
|
615
|
+
)
|
616
|
+
)
|
617
|
+
resnets.append(CosmosResnetBlock3d(in_channels, in_channels, dropout, num_groups))
|
618
|
+
|
619
|
+
self.resnets = nn.ModuleList(resnets)
|
620
|
+
self.attentions = nn.ModuleList(attentions)
|
621
|
+
self.temp_attentions = nn.ModuleList(temp_attentions)
|
622
|
+
|
623
|
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
624
|
+
hidden_states = self.resnets[0](hidden_states)
|
625
|
+
|
626
|
+
for attention, temp_attention, resnet in zip(self.attentions, self.temp_attentions, self.resnets[1:]):
|
627
|
+
num_frames = hidden_states.size(2)
|
628
|
+
attention_mask = torch.tril(hidden_states.new_ones(num_frames, num_frames)).bool()
|
629
|
+
|
630
|
+
hidden_states = attention(hidden_states)
|
631
|
+
hidden_states = temp_attention(hidden_states, attention_mask)
|
632
|
+
hidden_states = resnet(hidden_states)
|
633
|
+
|
634
|
+
return hidden_states
|
635
|
+
|
636
|
+
|
637
|
+
class CosmosUpBlock3d(nn.Module):
|
638
|
+
def __init__(
|
639
|
+
self,
|
640
|
+
in_channels: int,
|
641
|
+
out_channels: int,
|
642
|
+
num_layers: int,
|
643
|
+
dropout: float,
|
644
|
+
use_attention: bool,
|
645
|
+
use_upsample: bool,
|
646
|
+
spatial_upsample: bool,
|
647
|
+
temporal_upsample: bool,
|
648
|
+
) -> None:
|
649
|
+
super().__init__()
|
650
|
+
|
651
|
+
resnets, attention, temp_attentions = [], [], []
|
652
|
+
in_channel, out_channel = in_channels, out_channels
|
653
|
+
|
654
|
+
for _ in range(num_layers):
|
655
|
+
resnets.append(CosmosResnetBlock3d(in_channel, out_channel, dropout, num_groups=1))
|
656
|
+
in_channel = out_channel
|
657
|
+
|
658
|
+
if use_attention:
|
659
|
+
attention.append(
|
660
|
+
CosmosCausalAttention(
|
661
|
+
num_attention_heads=1,
|
662
|
+
attention_head_dim=out_channel,
|
663
|
+
num_groups=1,
|
664
|
+
dropout=dropout,
|
665
|
+
processor=CosmosSpatialAttentionProcessor2_0(),
|
666
|
+
)
|
667
|
+
)
|
668
|
+
temp_attentions.append(
|
669
|
+
CosmosCausalAttention(
|
670
|
+
num_attention_heads=1,
|
671
|
+
attention_head_dim=out_channel,
|
672
|
+
num_groups=1,
|
673
|
+
dropout=dropout,
|
674
|
+
processor=CosmosTemporalAttentionProcessor2_0(),
|
675
|
+
)
|
676
|
+
)
|
677
|
+
else:
|
678
|
+
attention.append(None)
|
679
|
+
temp_attentions.append(None)
|
680
|
+
|
681
|
+
self.resnets = nn.ModuleList(resnets)
|
682
|
+
self.attentions = nn.ModuleList(attention)
|
683
|
+
self.temp_attentions = nn.ModuleList(temp_attentions)
|
684
|
+
|
685
|
+
self.upsamplers = None
|
686
|
+
if use_upsample:
|
687
|
+
self.upsamplers = nn.ModuleList([])
|
688
|
+
self.upsamplers.append(CosmosUpsample3d(out_channel, spatial_upsample, temporal_upsample))
|
689
|
+
|
690
|
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
691
|
+
for resnet, attention, temp_attention in zip(self.resnets, self.attentions, self.temp_attentions):
|
692
|
+
hidden_states = resnet(hidden_states)
|
693
|
+
if attention is not None:
|
694
|
+
hidden_states = attention(hidden_states)
|
695
|
+
if temp_attention is not None:
|
696
|
+
num_frames = hidden_states.size(2)
|
697
|
+
attention_mask = torch.tril(hidden_states.new_ones(num_frames, num_frames)).bool()
|
698
|
+
hidden_states = temp_attention(hidden_states, attention_mask)
|
699
|
+
|
700
|
+
if self.upsamplers is not None:
|
701
|
+
for upsampler in self.upsamplers:
|
702
|
+
hidden_states = upsampler(hidden_states)
|
703
|
+
|
704
|
+
return hidden_states
|
705
|
+
|
706
|
+
|
707
|
+
class CosmosEncoder3d(nn.Module):
|
708
|
+
def __init__(
|
709
|
+
self,
|
710
|
+
in_channels: int = 3,
|
711
|
+
out_channels: int = 16,
|
712
|
+
block_out_channels: Tuple[int, ...] = (128, 256, 512, 512),
|
713
|
+
num_resnet_blocks: int = 2,
|
714
|
+
attention_resolutions: Tuple[int, ...] = (32,),
|
715
|
+
resolution: int = 1024,
|
716
|
+
patch_size: int = 4,
|
717
|
+
patch_type: str = "haar",
|
718
|
+
dropout: float = 0.0,
|
719
|
+
spatial_compression_ratio: int = 8,
|
720
|
+
temporal_compression_ratio: int = 8,
|
721
|
+
) -> None:
|
722
|
+
super().__init__()
|
723
|
+
inner_dim = in_channels * patch_size**3
|
724
|
+
num_spatial_layers = int(math.log2(spatial_compression_ratio)) - int(math.log2(patch_size))
|
725
|
+
num_temporal_layers = int(math.log2(temporal_compression_ratio)) - int(math.log2(patch_size))
|
726
|
+
|
727
|
+
# 1. Input patching & projection
|
728
|
+
self.patch_embed = CosmosPatchEmbed3d(patch_size, patch_type)
|
729
|
+
|
730
|
+
self.conv_in = CosmosConvProjection3d(inner_dim, block_out_channels[0])
|
731
|
+
|
732
|
+
# 2. Down blocks
|
733
|
+
current_resolution = resolution // patch_size
|
734
|
+
down_blocks = []
|
735
|
+
for i in range(len(block_out_channels) - 1):
|
736
|
+
in_channel = block_out_channels[i]
|
737
|
+
out_channel = block_out_channels[i + 1]
|
738
|
+
|
739
|
+
use_attention = current_resolution in attention_resolutions
|
740
|
+
spatial_downsample = temporal_downsample = False
|
741
|
+
if i < len(block_out_channels) - 2:
|
742
|
+
use_downsample = True
|
743
|
+
spatial_downsample = i < num_spatial_layers
|
744
|
+
temporal_downsample = i < num_temporal_layers
|
745
|
+
current_resolution = current_resolution // 2
|
746
|
+
else:
|
747
|
+
use_downsample = False
|
748
|
+
|
749
|
+
down_blocks.append(
|
750
|
+
CosmosDownBlock3d(
|
751
|
+
in_channel,
|
752
|
+
out_channel,
|
753
|
+
num_resnet_blocks,
|
754
|
+
dropout,
|
755
|
+
use_attention,
|
756
|
+
use_downsample,
|
757
|
+
spatial_downsample,
|
758
|
+
temporal_downsample,
|
759
|
+
)
|
760
|
+
)
|
761
|
+
self.down_blocks = nn.ModuleList(down_blocks)
|
762
|
+
|
763
|
+
# 3. Mid block
|
764
|
+
self.mid_block = CosmosMidBlock3d(block_out_channels[-1], num_layers=1, dropout=dropout, num_groups=1)
|
765
|
+
|
766
|
+
# 4. Output norm & projection
|
767
|
+
self.norm_out = CosmosCausalGroupNorm(block_out_channels[-1], num_groups=1)
|
768
|
+
self.conv_out = CosmosConvProjection3d(block_out_channels[-1], out_channels)
|
769
|
+
|
770
|
+
self.gradient_checkpointing = False
|
771
|
+
|
772
|
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
773
|
+
hidden_states = self.patch_embed(hidden_states)
|
774
|
+
hidden_states = self.conv_in(hidden_states)
|
775
|
+
|
776
|
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
777
|
+
for block in self.down_blocks:
|
778
|
+
hidden_states = self._gradient_checkpointing_func(block, hidden_states)
|
779
|
+
hidden_states = self._gradient_checkpointing_func(self.mid_block, hidden_states)
|
780
|
+
else:
|
781
|
+
for block in self.down_blocks:
|
782
|
+
hidden_states = block(hidden_states)
|
783
|
+
hidden_states = self.mid_block(hidden_states)
|
784
|
+
|
785
|
+
hidden_states = self.norm_out(hidden_states)
|
786
|
+
hidden_states = F.silu(hidden_states)
|
787
|
+
hidden_states = self.conv_out(hidden_states)
|
788
|
+
return hidden_states
|
789
|
+
|
790
|
+
|
791
|
+
class CosmosDecoder3d(nn.Module):
|
792
|
+
def __init__(
|
793
|
+
self,
|
794
|
+
in_channels: int = 16,
|
795
|
+
out_channels: int = 3,
|
796
|
+
block_out_channels: Tuple[int, ...] = (128, 256, 512, 512),
|
797
|
+
num_resnet_blocks: int = 2,
|
798
|
+
attention_resolutions: Tuple[int, ...] = (32,),
|
799
|
+
resolution: int = 1024,
|
800
|
+
patch_size: int = 4,
|
801
|
+
patch_type: str = "haar",
|
802
|
+
dropout: float = 0.0,
|
803
|
+
spatial_compression_ratio: int = 8,
|
804
|
+
temporal_compression_ratio: int = 8,
|
805
|
+
) -> None:
|
806
|
+
super().__init__()
|
807
|
+
inner_dim = out_channels * patch_size**3
|
808
|
+
num_spatial_layers = int(math.log2(spatial_compression_ratio)) - int(math.log2(patch_size))
|
809
|
+
num_temporal_layers = int(math.log2(temporal_compression_ratio)) - int(math.log2(patch_size))
|
810
|
+
reversed_block_out_channels = list(reversed(block_out_channels))
|
811
|
+
|
812
|
+
# 1. Input projection
|
813
|
+
self.conv_in = CosmosConvProjection3d(in_channels, reversed_block_out_channels[0])
|
814
|
+
|
815
|
+
# 2. Mid block
|
816
|
+
self.mid_block = CosmosMidBlock3d(reversed_block_out_channels[0], num_layers=1, dropout=dropout, num_groups=1)
|
817
|
+
|
818
|
+
# 3. Up blocks
|
819
|
+
current_resolution = (resolution // patch_size) // 2 ** (len(block_out_channels) - 2)
|
820
|
+
up_blocks = []
|
821
|
+
for i in range(len(block_out_channels) - 1):
|
822
|
+
in_channel = reversed_block_out_channels[i]
|
823
|
+
out_channel = reversed_block_out_channels[i + 1]
|
824
|
+
|
825
|
+
use_attention = current_resolution in attention_resolutions
|
826
|
+
spatial_upsample = temporal_upsample = False
|
827
|
+
if i < len(block_out_channels) - 2:
|
828
|
+
use_upsample = True
|
829
|
+
temporal_upsample = 0 < i < num_temporal_layers + 1
|
830
|
+
spatial_upsample = temporal_upsample or (
|
831
|
+
i < num_spatial_layers and num_spatial_layers > num_temporal_layers
|
832
|
+
)
|
833
|
+
current_resolution = current_resolution * 2
|
834
|
+
else:
|
835
|
+
use_upsample = False
|
836
|
+
|
837
|
+
up_blocks.append(
|
838
|
+
CosmosUpBlock3d(
|
839
|
+
in_channel,
|
840
|
+
out_channel,
|
841
|
+
num_resnet_blocks + 1,
|
842
|
+
dropout,
|
843
|
+
use_attention,
|
844
|
+
use_upsample,
|
845
|
+
spatial_upsample,
|
846
|
+
temporal_upsample,
|
847
|
+
)
|
848
|
+
)
|
849
|
+
self.up_blocks = nn.ModuleList(up_blocks)
|
850
|
+
|
851
|
+
# 4. Output norm & projection & unpatching
|
852
|
+
self.norm_out = CosmosCausalGroupNorm(reversed_block_out_channels[-1], num_groups=1)
|
853
|
+
self.conv_out = CosmosConvProjection3d(reversed_block_out_channels[-1], inner_dim)
|
854
|
+
|
855
|
+
self.unpatch_embed = CosmosUnpatcher3d(patch_size, patch_type)
|
856
|
+
|
857
|
+
self.gradient_checkpointing = False
|
858
|
+
|
859
|
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
860
|
+
hidden_states = self.conv_in(hidden_states)
|
861
|
+
hidden_states = self.mid_block(hidden_states)
|
862
|
+
|
863
|
+
for block in self.up_blocks:
|
864
|
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
865
|
+
hidden_states = self._gradient_checkpointing_func(block, hidden_states)
|
866
|
+
else:
|
867
|
+
hidden_states = block(hidden_states)
|
868
|
+
|
869
|
+
hidden_states = self.norm_out(hidden_states)
|
870
|
+
hidden_states = F.silu(hidden_states)
|
871
|
+
hidden_states = self.conv_out(hidden_states)
|
872
|
+
hidden_states = self.unpatch_embed(hidden_states)
|
873
|
+
return hidden_states
|
874
|
+
|
875
|
+
|
876
|
+
class AutoencoderKLCosmos(ModelMixin, ConfigMixin):
|
877
|
+
r"""
|
878
|
+
Autoencoder used in [Cosmos](https://huggingface.co/papers/2501.03575).
|
879
|
+
|
880
|
+
Args:
|
881
|
+
in_channels (`int`, defaults to `3`):
|
882
|
+
Number of input channels.
|
883
|
+
out_channels (`int`, defaults to `3`):
|
884
|
+
Number of output channels.
|
885
|
+
latent_channels (`int`, defaults to `16`):
|
886
|
+
Number of latent channels.
|
887
|
+
encoder_block_out_channels (`Tuple[int, ...]`, defaults to `(128, 256, 512, 512)`):
|
888
|
+
Number of output channels for each encoder down block.
|
889
|
+
decode_block_out_channels (`Tuple[int, ...]`, defaults to `(256, 512, 512, 512)`):
|
890
|
+
Number of output channels for each decoder up block.
|
891
|
+
attention_resolutions (`Tuple[int, ...]`, defaults to `(32,)`):
|
892
|
+
List of image/video resolutions at which to apply attention.
|
893
|
+
resolution (`int`, defaults to `1024`):
|
894
|
+
Base image/video resolution used for computing whether a block should have attention layers.
|
895
|
+
num_layers (`int`, defaults to `2`):
|
896
|
+
Number of resnet blocks in each encoder/decoder block.
|
897
|
+
patch_size (`int`, defaults to `4`):
|
898
|
+
Patch size used for patching the input image/video.
|
899
|
+
patch_type (`str`, defaults to `haar`):
|
900
|
+
Patch type used for patching the input image/video. Can be either `haar` or `rearrange`.
|
901
|
+
scaling_factor (`float`, defaults to `1.0`):
|
902
|
+
The component-wise standard deviation of the trained latent space computed using the first batch of the
|
903
|
+
training set. This is used to scale the latent space to have unit variance when training the diffusion
|
904
|
+
model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
|
905
|
+
diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
|
906
|
+
/ scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
|
907
|
+
Synthesis with Latent Diffusion Models](https://huggingface.co/papers/2112.10752) paper. Not applicable in
|
908
|
+
Cosmos, but we default to 1.0 for consistency.
|
909
|
+
spatial_compression_ratio (`int`, defaults to `8`):
|
910
|
+
The spatial compression ratio to apply in the VAE. The number of downsample blocks is determined using
|
911
|
+
this.
|
912
|
+
temporal_compression_ratio (`int`, defaults to `8`):
|
913
|
+
The temporal compression ratio to apply in the VAE. The number of downsample blocks is determined using
|
914
|
+
this.
|
915
|
+
"""
|
916
|
+
|
917
|
+
_supports_gradient_checkpointing = True
|
918
|
+
|
919
|
+
@register_to_config
|
920
|
+
def __init__(
|
921
|
+
self,
|
922
|
+
in_channels: int = 3,
|
923
|
+
out_channels: int = 3,
|
924
|
+
latent_channels: int = 16,
|
925
|
+
encoder_block_out_channels: Tuple[int, ...] = (128, 256, 512, 512),
|
926
|
+
decode_block_out_channels: Tuple[int, ...] = (256, 512, 512, 512),
|
927
|
+
attention_resolutions: Tuple[int, ...] = (32,),
|
928
|
+
resolution: int = 1024,
|
929
|
+
num_layers: int = 2,
|
930
|
+
patch_size: int = 4,
|
931
|
+
patch_type: str = "haar",
|
932
|
+
scaling_factor: float = 1.0,
|
933
|
+
spatial_compression_ratio: int = 8,
|
934
|
+
temporal_compression_ratio: int = 8,
|
935
|
+
latents_mean: Optional[List[float]] = LATENTS_MEAN,
|
936
|
+
latents_std: Optional[List[float]] = LATENTS_STD,
|
937
|
+
) -> None:
|
938
|
+
super().__init__()
|
939
|
+
|
940
|
+
self.encoder = CosmosEncoder3d(
|
941
|
+
in_channels=in_channels,
|
942
|
+
out_channels=latent_channels,
|
943
|
+
block_out_channels=encoder_block_out_channels,
|
944
|
+
num_resnet_blocks=num_layers,
|
945
|
+
attention_resolutions=attention_resolutions,
|
946
|
+
resolution=resolution,
|
947
|
+
patch_size=patch_size,
|
948
|
+
patch_type=patch_type,
|
949
|
+
spatial_compression_ratio=spatial_compression_ratio,
|
950
|
+
temporal_compression_ratio=temporal_compression_ratio,
|
951
|
+
)
|
952
|
+
self.decoder = CosmosDecoder3d(
|
953
|
+
in_channels=latent_channels,
|
954
|
+
out_channels=out_channels,
|
955
|
+
block_out_channels=decode_block_out_channels,
|
956
|
+
num_resnet_blocks=num_layers,
|
957
|
+
attention_resolutions=attention_resolutions,
|
958
|
+
resolution=resolution,
|
959
|
+
patch_size=patch_size,
|
960
|
+
patch_type=patch_type,
|
961
|
+
spatial_compression_ratio=spatial_compression_ratio,
|
962
|
+
temporal_compression_ratio=temporal_compression_ratio,
|
963
|
+
)
|
964
|
+
|
965
|
+
self.quant_conv = CosmosCausalConv3d(latent_channels, latent_channels, kernel_size=1, padding=0)
|
966
|
+
self.post_quant_conv = CosmosCausalConv3d(latent_channels, latent_channels, kernel_size=1, padding=0)
|
967
|
+
|
968
|
+
# When decoding a batch of video latents at a time, one can save memory by slicing across the batch dimension
|
969
|
+
# to perform decoding of a single video latent at a time.
|
970
|
+
self.use_slicing = False
|
971
|
+
|
972
|
+
# When decoding spatially large video latents, the memory requirement is very high. By breaking the video latent
|
973
|
+
# frames spatially into smaller tiles and performing multiple forward passes for decoding, and then blending the
|
974
|
+
# intermediate tiles together, the memory requirement can be lowered.
|
975
|
+
self.use_tiling = False
|
976
|
+
|
977
|
+
# When decoding temporally long video latents, the memory requirement is very high. By decoding latent frames
|
978
|
+
# at a fixed frame batch size (based on `self.num_latent_frames_batch_sizes`), the memory requirement can be lowered.
|
979
|
+
self.use_framewise_encoding = False
|
980
|
+
self.use_framewise_decoding = False
|
981
|
+
|
982
|
+
# This can be configured based on the amount of GPU memory available.
|
983
|
+
# `16` for sample frames and `2` for latent frames are sensible defaults for consumer GPUs.
|
984
|
+
# Setting it to higher values results in higher memory usage.
|
985
|
+
self.num_sample_frames_batch_size = 16
|
986
|
+
self.num_latent_frames_batch_size = 2
|
987
|
+
|
988
|
+
# The minimal tile height and width for spatial tiling to be used
|
989
|
+
self.tile_sample_min_height = 512
|
990
|
+
self.tile_sample_min_width = 512
|
991
|
+
self.tile_sample_min_num_frames = 16
|
992
|
+
|
993
|
+
# The minimal distance between two spatial tiles
|
994
|
+
self.tile_sample_stride_height = 448
|
995
|
+
self.tile_sample_stride_width = 448
|
996
|
+
self.tile_sample_stride_num_frames = 8
|
997
|
+
|
998
|
+
def enable_tiling(
|
999
|
+
self,
|
1000
|
+
tile_sample_min_height: Optional[int] = None,
|
1001
|
+
tile_sample_min_width: Optional[int] = None,
|
1002
|
+
tile_sample_min_num_frames: Optional[int] = None,
|
1003
|
+
tile_sample_stride_height: Optional[float] = None,
|
1004
|
+
tile_sample_stride_width: Optional[float] = None,
|
1005
|
+
tile_sample_stride_num_frames: Optional[float] = None,
|
1006
|
+
) -> None:
|
1007
|
+
r"""
|
1008
|
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
1009
|
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
1010
|
+
processing larger images.
|
1011
|
+
|
1012
|
+
Args:
|
1013
|
+
tile_sample_min_height (`int`, *optional*):
|
1014
|
+
The minimum height required for a sample to be separated into tiles across the height dimension.
|
1015
|
+
tile_sample_min_width (`int`, *optional*):
|
1016
|
+
The minimum width required for a sample to be separated into tiles across the width dimension.
|
1017
|
+
tile_sample_stride_height (`int`, *optional*):
|
1018
|
+
The minimum amount of overlap between two consecutive vertical tiles. This is to ensure that there are
|
1019
|
+
no tiling artifacts produced across the height dimension.
|
1020
|
+
tile_sample_stride_width (`int`, *optional*):
|
1021
|
+
The stride between two consecutive horizontal tiles. This is to ensure that there are no tiling
|
1022
|
+
artifacts produced across the width dimension.
|
1023
|
+
"""
|
1024
|
+
self.use_tiling = True
|
1025
|
+
self.tile_sample_min_height = tile_sample_min_height or self.tile_sample_min_height
|
1026
|
+
self.tile_sample_min_width = tile_sample_min_width or self.tile_sample_min_width
|
1027
|
+
self.tile_sample_min_num_frames = tile_sample_min_num_frames or self.tile_sample_min_num_frames
|
1028
|
+
self.tile_sample_stride_height = tile_sample_stride_height or self.tile_sample_stride_height
|
1029
|
+
self.tile_sample_stride_width = tile_sample_stride_width or self.tile_sample_stride_width
|
1030
|
+
self.tile_sample_stride_num_frames = tile_sample_stride_num_frames or self.tile_sample_stride_num_frames
|
1031
|
+
|
1032
|
+
def disable_tiling(self) -> None:
|
1033
|
+
r"""
|
1034
|
+
Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
|
1035
|
+
decoding in one step.
|
1036
|
+
"""
|
1037
|
+
self.use_tiling = False
|
1038
|
+
|
1039
|
+
def enable_slicing(self) -> None:
|
1040
|
+
r"""
|
1041
|
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
1042
|
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
1043
|
+
"""
|
1044
|
+
self.use_slicing = True
|
1045
|
+
|
1046
|
+
def disable_slicing(self) -> None:
|
1047
|
+
r"""
|
1048
|
+
Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
|
1049
|
+
decoding in one step.
|
1050
|
+
"""
|
1051
|
+
self.use_slicing = False
|
1052
|
+
|
1053
|
+
def _encode(self, x: torch.Tensor) -> torch.Tensor:
|
1054
|
+
x = self.encoder(x)
|
1055
|
+
enc = self.quant_conv(x)
|
1056
|
+
return enc
|
1057
|
+
|
1058
|
+
@apply_forward_hook
|
1059
|
+
def encode(self, x: torch.Tensor, return_dict: bool = True) -> torch.Tensor:
|
1060
|
+
if self.use_slicing and x.shape[0] > 1:
|
1061
|
+
encoded_slices = [self._encode(x_slice) for x_slice in x.split(1)]
|
1062
|
+
h = torch.cat(encoded_slices)
|
1063
|
+
else:
|
1064
|
+
h = self._encode(x)
|
1065
|
+
|
1066
|
+
posterior = IdentityDistribution(h)
|
1067
|
+
|
1068
|
+
if not return_dict:
|
1069
|
+
return (posterior,)
|
1070
|
+
return AutoencoderKLOutput(latent_dist=posterior)
|
1071
|
+
|
1072
|
+
def _decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, Tuple[torch.Tensor]]:
|
1073
|
+
z = self.post_quant_conv(z)
|
1074
|
+
dec = self.decoder(z)
|
1075
|
+
|
1076
|
+
if not return_dict:
|
1077
|
+
return (dec,)
|
1078
|
+
return DecoderOutput(sample=dec)
|
1079
|
+
|
1080
|
+
@apply_forward_hook
|
1081
|
+
def decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, Tuple[torch.Tensor]]:
|
1082
|
+
if self.use_slicing and z.shape[0] > 1:
|
1083
|
+
decoded_slices = [self._decode(z_slice).sample for z_slice in z.split(1)]
|
1084
|
+
decoded = torch.cat(decoded_slices)
|
1085
|
+
else:
|
1086
|
+
decoded = self._decode(z).sample
|
1087
|
+
|
1088
|
+
if not return_dict:
|
1089
|
+
return (decoded,)
|
1090
|
+
return DecoderOutput(sample=decoded)
|
1091
|
+
|
1092
|
+
def forward(
|
1093
|
+
self,
|
1094
|
+
sample: torch.Tensor,
|
1095
|
+
sample_posterior: bool = False,
|
1096
|
+
return_dict: bool = True,
|
1097
|
+
generator: Optional[torch.Generator] = None,
|
1098
|
+
) -> Union[Tuple[torch.Tensor], DecoderOutput]:
|
1099
|
+
x = sample
|
1100
|
+
posterior = self.encode(x).latent_dist
|
1101
|
+
if sample_posterior:
|
1102
|
+
z = posterior.sample(generator=generator)
|
1103
|
+
else:
|
1104
|
+
z = posterior.mode()
|
1105
|
+
dec = self.decode(z).sample
|
1106
|
+
if not return_dict:
|
1107
|
+
return (dec,)
|
1108
|
+
return DecoderOutput(sample=dec)
|