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,813 @@
|
|
1
|
+
# Copyright 2024 Marigold authors, PRS ETH Zurich. All rights reserved.
|
2
|
+
# Copyright 2024 The HuggingFace Team. 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
|
+
# More information and citation instructions are available on the
|
17
|
+
# Marigold project website: https://marigoldmonodepth.github.io
|
18
|
+
# --------------------------------------------------------------------------
|
19
|
+
from dataclasses import dataclass
|
20
|
+
from functools import partial
|
21
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
22
|
+
|
23
|
+
import numpy as np
|
24
|
+
import torch
|
25
|
+
from PIL import Image
|
26
|
+
from tqdm.auto import tqdm
|
27
|
+
from transformers import CLIPTextModel, CLIPTokenizer
|
28
|
+
|
29
|
+
from ...image_processor import PipelineImageInput
|
30
|
+
from ...models import (
|
31
|
+
AutoencoderKL,
|
32
|
+
UNet2DConditionModel,
|
33
|
+
)
|
34
|
+
from ...schedulers import (
|
35
|
+
DDIMScheduler,
|
36
|
+
LCMScheduler,
|
37
|
+
)
|
38
|
+
from ...utils import (
|
39
|
+
BaseOutput,
|
40
|
+
logging,
|
41
|
+
replace_example_docstring,
|
42
|
+
)
|
43
|
+
from ...utils.import_utils import is_scipy_available
|
44
|
+
from ...utils.torch_utils import randn_tensor
|
45
|
+
from ..pipeline_utils import DiffusionPipeline
|
46
|
+
from .marigold_image_processing import MarigoldImageProcessor
|
47
|
+
|
48
|
+
|
49
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
50
|
+
|
51
|
+
|
52
|
+
EXAMPLE_DOC_STRING = """
|
53
|
+
Examples:
|
54
|
+
```py
|
55
|
+
>>> import diffusers
|
56
|
+
>>> import torch
|
57
|
+
|
58
|
+
>>> pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
|
59
|
+
... "prs-eth/marigold-depth-lcm-v1-0", variant="fp16", torch_dtype=torch.float16
|
60
|
+
... ).to("cuda")
|
61
|
+
|
62
|
+
>>> image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")
|
63
|
+
>>> depth = pipe(image)
|
64
|
+
|
65
|
+
>>> vis = pipe.image_processor.visualize_depth(depth.prediction)
|
66
|
+
>>> vis[0].save("einstein_depth.png")
|
67
|
+
|
68
|
+
>>> depth_16bit = pipe.image_processor.export_depth_to_16bit_png(depth.prediction)
|
69
|
+
>>> depth_16bit[0].save("einstein_depth_16bit.png")
|
70
|
+
```
|
71
|
+
"""
|
72
|
+
|
73
|
+
|
74
|
+
@dataclass
|
75
|
+
class MarigoldDepthOutput(BaseOutput):
|
76
|
+
"""
|
77
|
+
Output class for Marigold monocular depth prediction pipeline.
|
78
|
+
|
79
|
+
Args:
|
80
|
+
prediction (`np.ndarray`, `torch.Tensor`):
|
81
|
+
Predicted depth maps with values in the range [0, 1]. The shape is always $numimages \times 1 \times height
|
82
|
+
\times width$, regardless of whether the images were passed as a 4D array or a list.
|
83
|
+
uncertainty (`None`, `np.ndarray`, `torch.Tensor`):
|
84
|
+
Uncertainty maps computed from the ensemble, with values in the range [0, 1]. The shape is $numimages
|
85
|
+
\times 1 \times height \times width$.
|
86
|
+
latent (`None`, `torch.Tensor`):
|
87
|
+
Latent features corresponding to the predictions, compatible with the `latents` argument of the pipeline.
|
88
|
+
The shape is $numimages * numensemble \times 4 \times latentheight \times latentwidth$.
|
89
|
+
"""
|
90
|
+
|
91
|
+
prediction: Union[np.ndarray, torch.Tensor]
|
92
|
+
uncertainty: Union[None, np.ndarray, torch.Tensor]
|
93
|
+
latent: Union[None, torch.Tensor]
|
94
|
+
|
95
|
+
|
96
|
+
class MarigoldDepthPipeline(DiffusionPipeline):
|
97
|
+
"""
|
98
|
+
Pipeline for monocular depth estimation using the Marigold method: https://marigoldmonodepth.github.io.
|
99
|
+
|
100
|
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
101
|
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
102
|
+
|
103
|
+
Args:
|
104
|
+
unet (`UNet2DConditionModel`):
|
105
|
+
Conditional U-Net to denoise the depth latent, conditioned on image latent.
|
106
|
+
vae (`AutoencoderKL`):
|
107
|
+
Variational Auto-Encoder (VAE) Model to encode and decode images and predictions to and from latent
|
108
|
+
representations.
|
109
|
+
scheduler (`DDIMScheduler` or `LCMScheduler`):
|
110
|
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents.
|
111
|
+
text_encoder (`CLIPTextModel`):
|
112
|
+
Text-encoder, for empty text embedding.
|
113
|
+
tokenizer (`CLIPTokenizer`):
|
114
|
+
CLIP tokenizer.
|
115
|
+
prediction_type (`str`, *optional*):
|
116
|
+
Type of predictions made by the model.
|
117
|
+
scale_invariant (`bool`, *optional*):
|
118
|
+
A model property specifying whether the predicted depth maps are scale-invariant. This value must be set in
|
119
|
+
the model config. When used together with the `shift_invariant=True` flag, the model is also called
|
120
|
+
"affine-invariant". NB: overriding this value is not supported.
|
121
|
+
shift_invariant (`bool`, *optional*):
|
122
|
+
A model property specifying whether the predicted depth maps are shift-invariant. This value must be set in
|
123
|
+
the model config. When used together with the `scale_invariant=True` flag, the model is also called
|
124
|
+
"affine-invariant". NB: overriding this value is not supported.
|
125
|
+
default_denoising_steps (`int`, *optional*):
|
126
|
+
The minimum number of denoising diffusion steps that are required to produce a prediction of reasonable
|
127
|
+
quality with the given model. This value must be set in the model config. When the pipeline is called
|
128
|
+
without explicitly setting `num_inference_steps`, the default value is used. This is required to ensure
|
129
|
+
reasonable results with various model flavors compatible with the pipeline, such as those relying on very
|
130
|
+
short denoising schedules (`LCMScheduler`) and those with full diffusion schedules (`DDIMScheduler`).
|
131
|
+
default_processing_resolution (`int`, *optional*):
|
132
|
+
The recommended value of the `processing_resolution` parameter of the pipeline. This value must be set in
|
133
|
+
the model config. When the pipeline is called without explicitly setting `processing_resolution`, the
|
134
|
+
default value is used. This is required to ensure reasonable results with various model flavors trained
|
135
|
+
with varying optimal processing resolution values.
|
136
|
+
"""
|
137
|
+
|
138
|
+
model_cpu_offload_seq = "text_encoder->unet->vae"
|
139
|
+
supported_prediction_types = ("depth", "disparity")
|
140
|
+
|
141
|
+
def __init__(
|
142
|
+
self,
|
143
|
+
unet: UNet2DConditionModel,
|
144
|
+
vae: AutoencoderKL,
|
145
|
+
scheduler: Union[DDIMScheduler, LCMScheduler],
|
146
|
+
text_encoder: CLIPTextModel,
|
147
|
+
tokenizer: CLIPTokenizer,
|
148
|
+
prediction_type: Optional[str] = None,
|
149
|
+
scale_invariant: Optional[bool] = True,
|
150
|
+
shift_invariant: Optional[bool] = True,
|
151
|
+
default_denoising_steps: Optional[int] = None,
|
152
|
+
default_processing_resolution: Optional[int] = None,
|
153
|
+
):
|
154
|
+
super().__init__()
|
155
|
+
|
156
|
+
if prediction_type not in self.supported_prediction_types:
|
157
|
+
logger.warning(
|
158
|
+
f"Potentially unsupported `prediction_type='{prediction_type}'`; values supported by the pipeline: "
|
159
|
+
f"{self.supported_prediction_types}."
|
160
|
+
)
|
161
|
+
|
162
|
+
self.register_modules(
|
163
|
+
unet=unet,
|
164
|
+
vae=vae,
|
165
|
+
scheduler=scheduler,
|
166
|
+
text_encoder=text_encoder,
|
167
|
+
tokenizer=tokenizer,
|
168
|
+
)
|
169
|
+
self.register_to_config(
|
170
|
+
prediction_type=prediction_type,
|
171
|
+
scale_invariant=scale_invariant,
|
172
|
+
shift_invariant=shift_invariant,
|
173
|
+
default_denoising_steps=default_denoising_steps,
|
174
|
+
default_processing_resolution=default_processing_resolution,
|
175
|
+
)
|
176
|
+
|
177
|
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
178
|
+
|
179
|
+
self.scale_invariant = scale_invariant
|
180
|
+
self.shift_invariant = shift_invariant
|
181
|
+
self.default_denoising_steps = default_denoising_steps
|
182
|
+
self.default_processing_resolution = default_processing_resolution
|
183
|
+
|
184
|
+
self.empty_text_embedding = None
|
185
|
+
|
186
|
+
self.image_processor = MarigoldImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
187
|
+
|
188
|
+
def check_inputs(
|
189
|
+
self,
|
190
|
+
image: PipelineImageInput,
|
191
|
+
num_inference_steps: int,
|
192
|
+
ensemble_size: int,
|
193
|
+
processing_resolution: int,
|
194
|
+
resample_method_input: str,
|
195
|
+
resample_method_output: str,
|
196
|
+
batch_size: int,
|
197
|
+
ensembling_kwargs: Optional[Dict[str, Any]],
|
198
|
+
latents: Optional[torch.Tensor],
|
199
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]],
|
200
|
+
output_type: str,
|
201
|
+
output_uncertainty: bool,
|
202
|
+
) -> int:
|
203
|
+
if num_inference_steps is None:
|
204
|
+
raise ValueError("`num_inference_steps` is not specified and could not be resolved from the model config.")
|
205
|
+
if num_inference_steps < 1:
|
206
|
+
raise ValueError("`num_inference_steps` must be positive.")
|
207
|
+
if ensemble_size < 1:
|
208
|
+
raise ValueError("`ensemble_size` must be positive.")
|
209
|
+
if ensemble_size == 2:
|
210
|
+
logger.warning(
|
211
|
+
"`ensemble_size` == 2 results are similar to no ensembling (1); "
|
212
|
+
"consider increasing the value to at least 3."
|
213
|
+
)
|
214
|
+
if ensemble_size > 1 and (self.scale_invariant or self.shift_invariant) and not is_scipy_available():
|
215
|
+
raise ImportError("Make sure to install scipy if you want to use ensembling.")
|
216
|
+
if ensemble_size == 1 and output_uncertainty:
|
217
|
+
raise ValueError(
|
218
|
+
"Computing uncertainty by setting `output_uncertainty=True` also requires setting `ensemble_size` "
|
219
|
+
"greater than 1."
|
220
|
+
)
|
221
|
+
if processing_resolution is None:
|
222
|
+
raise ValueError(
|
223
|
+
"`processing_resolution` is not specified and could not be resolved from the model config."
|
224
|
+
)
|
225
|
+
if processing_resolution < 0:
|
226
|
+
raise ValueError(
|
227
|
+
"`processing_resolution` must be non-negative: 0 for native resolution, or any positive value for "
|
228
|
+
"downsampled processing."
|
229
|
+
)
|
230
|
+
if processing_resolution % self.vae_scale_factor != 0:
|
231
|
+
raise ValueError(f"`processing_resolution` must be a multiple of {self.vae_scale_factor}.")
|
232
|
+
if resample_method_input not in ("nearest", "nearest-exact", "bilinear", "bicubic", "area"):
|
233
|
+
raise ValueError(
|
234
|
+
"`resample_method_input` takes string values compatible with PIL library: "
|
235
|
+
"nearest, nearest-exact, bilinear, bicubic, area."
|
236
|
+
)
|
237
|
+
if resample_method_output not in ("nearest", "nearest-exact", "bilinear", "bicubic", "area"):
|
238
|
+
raise ValueError(
|
239
|
+
"`resample_method_output` takes string values compatible with PIL library: "
|
240
|
+
"nearest, nearest-exact, bilinear, bicubic, area."
|
241
|
+
)
|
242
|
+
if batch_size < 1:
|
243
|
+
raise ValueError("`batch_size` must be positive.")
|
244
|
+
if output_type not in ["pt", "np"]:
|
245
|
+
raise ValueError("`output_type` must be one of `pt` or `np`.")
|
246
|
+
if latents is not None and generator is not None:
|
247
|
+
raise ValueError("`latents` and `generator` cannot be used together.")
|
248
|
+
if ensembling_kwargs is not None:
|
249
|
+
if not isinstance(ensembling_kwargs, dict):
|
250
|
+
raise ValueError("`ensembling_kwargs` must be a dictionary.")
|
251
|
+
if "reduction" in ensembling_kwargs and ensembling_kwargs["reduction"] not in ("mean", "median"):
|
252
|
+
raise ValueError("`ensembling_kwargs['reduction']` can be either `'mean'` or `'median'`.")
|
253
|
+
|
254
|
+
# image checks
|
255
|
+
num_images = 0
|
256
|
+
W, H = None, None
|
257
|
+
if not isinstance(image, list):
|
258
|
+
image = [image]
|
259
|
+
for i, img in enumerate(image):
|
260
|
+
if isinstance(img, np.ndarray) or torch.is_tensor(img):
|
261
|
+
if img.ndim not in (2, 3, 4):
|
262
|
+
raise ValueError(f"`image[{i}]` has unsupported dimensions or shape: {img.shape}.")
|
263
|
+
H_i, W_i = img.shape[-2:]
|
264
|
+
N_i = 1
|
265
|
+
if img.ndim == 4:
|
266
|
+
N_i = img.shape[0]
|
267
|
+
elif isinstance(img, Image.Image):
|
268
|
+
W_i, H_i = img.size
|
269
|
+
N_i = 1
|
270
|
+
else:
|
271
|
+
raise ValueError(f"Unsupported `image[{i}]` type: {type(img)}.")
|
272
|
+
if W is None:
|
273
|
+
W, H = W_i, H_i
|
274
|
+
elif (W, H) != (W_i, H_i):
|
275
|
+
raise ValueError(
|
276
|
+
f"Input `image[{i}]` has incompatible dimensions {(W_i, H_i)} with the previous images {(W, H)}"
|
277
|
+
)
|
278
|
+
num_images += N_i
|
279
|
+
|
280
|
+
# latents checks
|
281
|
+
if latents is not None:
|
282
|
+
if not torch.is_tensor(latents):
|
283
|
+
raise ValueError("`latents` must be a torch.Tensor.")
|
284
|
+
if latents.dim() != 4:
|
285
|
+
raise ValueError(f"`latents` has unsupported dimensions or shape: {latents.shape}.")
|
286
|
+
|
287
|
+
if processing_resolution > 0:
|
288
|
+
max_orig = max(H, W)
|
289
|
+
new_H = H * processing_resolution // max_orig
|
290
|
+
new_W = W * processing_resolution // max_orig
|
291
|
+
if new_H == 0 or new_W == 0:
|
292
|
+
raise ValueError(f"Extreme aspect ratio of the input image: [{W} x {H}]")
|
293
|
+
W, H = new_W, new_H
|
294
|
+
w = (W + self.vae_scale_factor - 1) // self.vae_scale_factor
|
295
|
+
h = (H + self.vae_scale_factor - 1) // self.vae_scale_factor
|
296
|
+
shape_expected = (num_images * ensemble_size, self.vae.config.latent_channels, h, w)
|
297
|
+
|
298
|
+
if latents.shape != shape_expected:
|
299
|
+
raise ValueError(f"`latents` has unexpected shape={latents.shape} expected={shape_expected}.")
|
300
|
+
|
301
|
+
# generator checks
|
302
|
+
if generator is not None:
|
303
|
+
if isinstance(generator, list):
|
304
|
+
if len(generator) != num_images * ensemble_size:
|
305
|
+
raise ValueError(
|
306
|
+
"The number of generators must match the total number of ensemble members for all input images."
|
307
|
+
)
|
308
|
+
if not all(g.device.type == generator[0].device.type for g in generator):
|
309
|
+
raise ValueError("`generator` device placement is not consistent in the list.")
|
310
|
+
elif not isinstance(generator, torch.Generator):
|
311
|
+
raise ValueError(f"Unsupported generator type: {type(generator)}.")
|
312
|
+
|
313
|
+
return num_images
|
314
|
+
|
315
|
+
def progress_bar(self, iterable=None, total=None, desc=None, leave=True):
|
316
|
+
if not hasattr(self, "_progress_bar_config"):
|
317
|
+
self._progress_bar_config = {}
|
318
|
+
elif not isinstance(self._progress_bar_config, dict):
|
319
|
+
raise ValueError(
|
320
|
+
f"`self._progress_bar_config` should be of type `dict`, but is {type(self._progress_bar_config)}."
|
321
|
+
)
|
322
|
+
|
323
|
+
progress_bar_config = dict(**self._progress_bar_config)
|
324
|
+
progress_bar_config["desc"] = progress_bar_config.get("desc", desc)
|
325
|
+
progress_bar_config["leave"] = progress_bar_config.get("leave", leave)
|
326
|
+
if iterable is not None:
|
327
|
+
return tqdm(iterable, **progress_bar_config)
|
328
|
+
elif total is not None:
|
329
|
+
return tqdm(total=total, **progress_bar_config)
|
330
|
+
else:
|
331
|
+
raise ValueError("Either `total` or `iterable` has to be defined.")
|
332
|
+
|
333
|
+
@torch.no_grad()
|
334
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
335
|
+
def __call__(
|
336
|
+
self,
|
337
|
+
image: PipelineImageInput,
|
338
|
+
num_inference_steps: Optional[int] = None,
|
339
|
+
ensemble_size: int = 1,
|
340
|
+
processing_resolution: Optional[int] = None,
|
341
|
+
match_input_resolution: bool = True,
|
342
|
+
resample_method_input: str = "bilinear",
|
343
|
+
resample_method_output: str = "bilinear",
|
344
|
+
batch_size: int = 1,
|
345
|
+
ensembling_kwargs: Optional[Dict[str, Any]] = None,
|
346
|
+
latents: Optional[Union[torch.Tensor, List[torch.Tensor]]] = None,
|
347
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
348
|
+
output_type: str = "np",
|
349
|
+
output_uncertainty: bool = False,
|
350
|
+
output_latent: bool = False,
|
351
|
+
return_dict: bool = True,
|
352
|
+
):
|
353
|
+
"""
|
354
|
+
Function invoked when calling the pipeline.
|
355
|
+
|
356
|
+
Args:
|
357
|
+
image (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`),
|
358
|
+
`List[torch.Tensor]`: An input image or images used as an input for the depth estimation task. For
|
359
|
+
arrays and tensors, the expected value range is between `[0, 1]`. Passing a batch of images is possible
|
360
|
+
by providing a four-dimensional array or a tensor. Additionally, a list of images of two- or
|
361
|
+
three-dimensional arrays or tensors can be passed. In the latter case, all list elements must have the
|
362
|
+
same width and height.
|
363
|
+
num_inference_steps (`int`, *optional*, defaults to `None`):
|
364
|
+
Number of denoising diffusion steps during inference. The default value `None` results in automatic
|
365
|
+
selection. The number of steps should be at least 10 with the full Marigold models, and between 1 and 4
|
366
|
+
for Marigold-LCM models.
|
367
|
+
ensemble_size (`int`, defaults to `1`):
|
368
|
+
Number of ensemble predictions. Recommended values are 5 and higher for better precision, or 1 for
|
369
|
+
faster inference.
|
370
|
+
processing_resolution (`int`, *optional*, defaults to `None`):
|
371
|
+
Effective processing resolution. When set to `0`, matches the larger input image dimension. This
|
372
|
+
produces crisper predictions, but may also lead to the overall loss of global context. The default
|
373
|
+
value `None` resolves to the optimal value from the model config.
|
374
|
+
match_input_resolution (`bool`, *optional*, defaults to `True`):
|
375
|
+
When enabled, the output prediction is resized to match the input dimensions. When disabled, the longer
|
376
|
+
side of the output will equal to `processing_resolution`.
|
377
|
+
resample_method_input (`str`, *optional*, defaults to `"bilinear"`):
|
378
|
+
Resampling method used to resize input images to `processing_resolution`. The accepted values are:
|
379
|
+
`"nearest"`, `"nearest-exact"`, `"bilinear"`, `"bicubic"`, or `"area"`.
|
380
|
+
resample_method_output (`str`, *optional*, defaults to `"bilinear"`):
|
381
|
+
Resampling method used to resize output predictions to match the input resolution. The accepted values
|
382
|
+
are `"nearest"`, `"nearest-exact"`, `"bilinear"`, `"bicubic"`, or `"area"`.
|
383
|
+
batch_size (`int`, *optional*, defaults to `1`):
|
384
|
+
Batch size; only matters when setting `ensemble_size` or passing a tensor of images.
|
385
|
+
ensembling_kwargs (`dict`, *optional*, defaults to `None`)
|
386
|
+
Extra dictionary with arguments for precise ensembling control. The following options are available:
|
387
|
+
- reduction (`str`, *optional*, defaults to `"median"`): Defines the ensembling function applied in
|
388
|
+
every pixel location, can be either `"median"` or `"mean"`.
|
389
|
+
- regularizer_strength (`float`, *optional*, defaults to `0.02`): Strength of the regularizer that
|
390
|
+
pulls the aligned predictions to the unit range from 0 to 1.
|
391
|
+
- max_iter (`int`, *optional*, defaults to `2`): Maximum number of the alignment solver steps. Refer to
|
392
|
+
`scipy.optimize.minimize` function, `options` argument.
|
393
|
+
- tol (`float`, *optional*, defaults to `1e-3`): Alignment solver tolerance. The solver stops when the
|
394
|
+
tolerance is reached.
|
395
|
+
- max_res (`int`, *optional*, defaults to `None`): Resolution at which the alignment is performed;
|
396
|
+
`None` matches the `processing_resolution`.
|
397
|
+
latents (`torch.Tensor`, or `List[torch.Tensor]`, *optional*, defaults to `None`):
|
398
|
+
Latent noise tensors to replace the random initialization. These can be taken from the previous
|
399
|
+
function call's output.
|
400
|
+
generator (`torch.Generator`, or `List[torch.Generator]`, *optional*, defaults to `None`):
|
401
|
+
Random number generator object to ensure reproducibility.
|
402
|
+
output_type (`str`, *optional*, defaults to `"np"`):
|
403
|
+
Preferred format of the output's `prediction` and the optional `uncertainty` fields. The accepted
|
404
|
+
values are: `"np"` (numpy array) or `"pt"` (torch tensor).
|
405
|
+
output_uncertainty (`bool`, *optional*, defaults to `False`):
|
406
|
+
When enabled, the output's `uncertainty` field contains the predictive uncertainty map, provided that
|
407
|
+
the `ensemble_size` argument is set to a value above 2.
|
408
|
+
output_latent (`bool`, *optional*, defaults to `False`):
|
409
|
+
When enabled, the output's `latent` field contains the latent codes corresponding to the predictions
|
410
|
+
within the ensemble. These codes can be saved, modified, and used for subsequent calls with the
|
411
|
+
`latents` argument.
|
412
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
413
|
+
Whether or not to return a [`~pipelines.marigold.MarigoldDepthOutput`] instead of a plain tuple.
|
414
|
+
|
415
|
+
Examples:
|
416
|
+
|
417
|
+
Returns:
|
418
|
+
[`~pipelines.marigold.MarigoldDepthOutput`] or `tuple`:
|
419
|
+
If `return_dict` is `True`, [`~pipelines.marigold.MarigoldDepthOutput`] is returned, otherwise a
|
420
|
+
`tuple` is returned where the first element is the prediction, the second element is the uncertainty
|
421
|
+
(or `None`), and the third is the latent (or `None`).
|
422
|
+
"""
|
423
|
+
|
424
|
+
# 0. Resolving variables.
|
425
|
+
device = self._execution_device
|
426
|
+
dtype = self.dtype
|
427
|
+
|
428
|
+
# Model-specific optimal default values leading to fast and reasonable results.
|
429
|
+
if num_inference_steps is None:
|
430
|
+
num_inference_steps = self.default_denoising_steps
|
431
|
+
if processing_resolution is None:
|
432
|
+
processing_resolution = self.default_processing_resolution
|
433
|
+
|
434
|
+
# 1. Check inputs.
|
435
|
+
num_images = self.check_inputs(
|
436
|
+
image,
|
437
|
+
num_inference_steps,
|
438
|
+
ensemble_size,
|
439
|
+
processing_resolution,
|
440
|
+
resample_method_input,
|
441
|
+
resample_method_output,
|
442
|
+
batch_size,
|
443
|
+
ensembling_kwargs,
|
444
|
+
latents,
|
445
|
+
generator,
|
446
|
+
output_type,
|
447
|
+
output_uncertainty,
|
448
|
+
)
|
449
|
+
|
450
|
+
# 2. Prepare empty text conditioning.
|
451
|
+
# Model invocation: self.tokenizer, self.text_encoder.
|
452
|
+
if self.empty_text_embedding is None:
|
453
|
+
prompt = ""
|
454
|
+
text_inputs = self.tokenizer(
|
455
|
+
prompt,
|
456
|
+
padding="do_not_pad",
|
457
|
+
max_length=self.tokenizer.model_max_length,
|
458
|
+
truncation=True,
|
459
|
+
return_tensors="pt",
|
460
|
+
)
|
461
|
+
text_input_ids = text_inputs.input_ids.to(device)
|
462
|
+
self.empty_text_embedding = self.text_encoder(text_input_ids)[0] # [1,2,1024]
|
463
|
+
|
464
|
+
# 3. Preprocess input images. This function loads input image or images of compatible dimensions `(H, W)`,
|
465
|
+
# optionally downsamples them to the `processing_resolution` `(PH, PW)`, where
|
466
|
+
# `max(PH, PW) == processing_resolution`, and pads the dimensions to `(PPH, PPW)` such that these values are
|
467
|
+
# divisible by the latent space downscaling factor (typically 8 in Stable Diffusion). The default value `None`
|
468
|
+
# of `processing_resolution` resolves to the optimal value from the model config. It is a recommended mode of
|
469
|
+
# operation and leads to the most reasonable results. Using the native image resolution or any other processing
|
470
|
+
# resolution can lead to loss of either fine details or global context in the output predictions.
|
471
|
+
image, padding, original_resolution = self.image_processor.preprocess(
|
472
|
+
image, processing_resolution, resample_method_input, device, dtype
|
473
|
+
) # [N,3,PPH,PPW]
|
474
|
+
|
475
|
+
# 4. Encode input image into latent space. At this step, each of the `N` input images is represented with `E`
|
476
|
+
# ensemble members. Each ensemble member is an independent diffused prediction, just initialized independently.
|
477
|
+
# Latents of each such predictions across all input images and all ensemble members are represented in the
|
478
|
+
# `pred_latent` variable. The variable `image_latent` is of the same shape: it contains each input image encoded
|
479
|
+
# into latent space and replicated `E` times. The latents can be either generated (see `generator` to ensure
|
480
|
+
# reproducibility), or passed explicitly via the `latents` argument. The latter can be set outside the pipeline
|
481
|
+
# code. For example, in the Marigold-LCM video processing demo, the latents initialization of a frame is taken
|
482
|
+
# as a convex combination of the latents output of the pipeline for the previous frame and a newly-sampled
|
483
|
+
# noise. This behavior can be achieved by setting the `output_latent` argument to `True`. The latent space
|
484
|
+
# dimensions are `(h, w)`. Encoding into latent space happens in batches of size `batch_size`.
|
485
|
+
# Model invocation: self.vae.encoder.
|
486
|
+
image_latent, pred_latent = self.prepare_latents(
|
487
|
+
image, latents, generator, ensemble_size, batch_size
|
488
|
+
) # [N*E,4,h,w], [N*E,4,h,w]
|
489
|
+
|
490
|
+
del image
|
491
|
+
|
492
|
+
batch_empty_text_embedding = self.empty_text_embedding.to(device=device, dtype=dtype).repeat(
|
493
|
+
batch_size, 1, 1
|
494
|
+
) # [B,1024,2]
|
495
|
+
|
496
|
+
# 5. Process the denoising loop. All `N * E` latents are processed sequentially in batches of size `batch_size`.
|
497
|
+
# The unet model takes concatenated latent spaces of the input image and the predicted modality as an input, and
|
498
|
+
# outputs noise for the predicted modality's latent space. The number of denoising diffusion steps is defined by
|
499
|
+
# `num_inference_steps`. It is either set directly, or resolves to the optimal value specific to the loaded
|
500
|
+
# model.
|
501
|
+
# Model invocation: self.unet.
|
502
|
+
pred_latents = []
|
503
|
+
|
504
|
+
for i in self.progress_bar(
|
505
|
+
range(0, num_images * ensemble_size, batch_size), leave=True, desc="Marigold predictions..."
|
506
|
+
):
|
507
|
+
batch_image_latent = image_latent[i : i + batch_size] # [B,4,h,w]
|
508
|
+
batch_pred_latent = pred_latent[i : i + batch_size] # [B,4,h,w]
|
509
|
+
effective_batch_size = batch_image_latent.shape[0]
|
510
|
+
text = batch_empty_text_embedding[:effective_batch_size] # [B,2,1024]
|
511
|
+
|
512
|
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
513
|
+
for t in self.progress_bar(self.scheduler.timesteps, leave=False, desc="Diffusion steps..."):
|
514
|
+
batch_latent = torch.cat([batch_image_latent, batch_pred_latent], dim=1) # [B,8,h,w]
|
515
|
+
noise = self.unet(batch_latent, t, encoder_hidden_states=text, return_dict=False)[0] # [B,4,h,w]
|
516
|
+
batch_pred_latent = self.scheduler.step(
|
517
|
+
noise, t, batch_pred_latent, generator=generator
|
518
|
+
).prev_sample # [B,4,h,w]
|
519
|
+
|
520
|
+
pred_latents.append(batch_pred_latent)
|
521
|
+
|
522
|
+
pred_latent = torch.cat(pred_latents, dim=0) # [N*E,4,h,w]
|
523
|
+
|
524
|
+
del (
|
525
|
+
pred_latents,
|
526
|
+
image_latent,
|
527
|
+
batch_empty_text_embedding,
|
528
|
+
batch_image_latent,
|
529
|
+
batch_pred_latent,
|
530
|
+
text,
|
531
|
+
batch_latent,
|
532
|
+
noise,
|
533
|
+
)
|
534
|
+
|
535
|
+
# 6. Decode predictions from latent into pixel space. The resulting `N * E` predictions have shape `(PPH, PPW)`,
|
536
|
+
# which requires slight postprocessing. Decoding into pixel space happens in batches of size `batch_size`.
|
537
|
+
# Model invocation: self.vae.decoder.
|
538
|
+
prediction = torch.cat(
|
539
|
+
[
|
540
|
+
self.decode_prediction(pred_latent[i : i + batch_size])
|
541
|
+
for i in range(0, pred_latent.shape[0], batch_size)
|
542
|
+
],
|
543
|
+
dim=0,
|
544
|
+
) # [N*E,1,PPH,PPW]
|
545
|
+
|
546
|
+
if not output_latent:
|
547
|
+
pred_latent = None
|
548
|
+
|
549
|
+
# 7. Remove padding. The output shape is (PH, PW).
|
550
|
+
prediction = self.image_processor.unpad_image(prediction, padding) # [N*E,1,PH,PW]
|
551
|
+
|
552
|
+
# 8. Ensemble and compute uncertainty (when `output_uncertainty` is set). This code treats each of the `N`
|
553
|
+
# groups of `E` ensemble predictions independently. For each group it computes an ensembled prediction of shape
|
554
|
+
# `(PH, PW)` and an optional uncertainty map of the same dimensions. After computing this pair of outputs for
|
555
|
+
# each group independently, it stacks them respectively into batches of `N` almost final predictions and
|
556
|
+
# uncertainty maps.
|
557
|
+
uncertainty = None
|
558
|
+
if ensemble_size > 1:
|
559
|
+
prediction = prediction.reshape(num_images, ensemble_size, *prediction.shape[1:]) # [N,E,1,PH,PW]
|
560
|
+
prediction = [
|
561
|
+
self.ensemble_depth(
|
562
|
+
prediction[i],
|
563
|
+
self.scale_invariant,
|
564
|
+
self.shift_invariant,
|
565
|
+
output_uncertainty,
|
566
|
+
**(ensembling_kwargs or {}),
|
567
|
+
)
|
568
|
+
for i in range(num_images)
|
569
|
+
] # [ [[1,1,PH,PW], [1,1,PH,PW]], ... ]
|
570
|
+
prediction, uncertainty = zip(*prediction) # [[1,1,PH,PW], ... ], [[1,1,PH,PW], ... ]
|
571
|
+
prediction = torch.cat(prediction, dim=0) # [N,1,PH,PW]
|
572
|
+
if output_uncertainty:
|
573
|
+
uncertainty = torch.cat(uncertainty, dim=0) # [N,1,PH,PW]
|
574
|
+
else:
|
575
|
+
uncertainty = None
|
576
|
+
|
577
|
+
# 9. If `match_input_resolution` is set, the output prediction and the uncertainty are upsampled to match the
|
578
|
+
# input resolution `(H, W)`. This step may introduce upsampling artifacts, and therefore can be disabled.
|
579
|
+
# Depending on the downstream use-case, upsampling can be also chosen based on the tolerated artifacts by
|
580
|
+
# setting the `resample_method_output` parameter (e.g., to `"nearest"`).
|
581
|
+
if match_input_resolution:
|
582
|
+
prediction = self.image_processor.resize_antialias(
|
583
|
+
prediction, original_resolution, resample_method_output, is_aa=False
|
584
|
+
) # [N,1,H,W]
|
585
|
+
if uncertainty is not None and output_uncertainty:
|
586
|
+
uncertainty = self.image_processor.resize_antialias(
|
587
|
+
uncertainty, original_resolution, resample_method_output, is_aa=False
|
588
|
+
) # [N,1,H,W]
|
589
|
+
|
590
|
+
# 10. Prepare the final outputs.
|
591
|
+
if output_type == "np":
|
592
|
+
prediction = self.image_processor.pt_to_numpy(prediction) # [N,H,W,1]
|
593
|
+
if uncertainty is not None and output_uncertainty:
|
594
|
+
uncertainty = self.image_processor.pt_to_numpy(uncertainty) # [N,H,W,1]
|
595
|
+
|
596
|
+
# 11. Offload all models
|
597
|
+
self.maybe_free_model_hooks()
|
598
|
+
|
599
|
+
if not return_dict:
|
600
|
+
return (prediction, uncertainty, pred_latent)
|
601
|
+
|
602
|
+
return MarigoldDepthOutput(
|
603
|
+
prediction=prediction,
|
604
|
+
uncertainty=uncertainty,
|
605
|
+
latent=pred_latent,
|
606
|
+
)
|
607
|
+
|
608
|
+
def prepare_latents(
|
609
|
+
self,
|
610
|
+
image: torch.Tensor,
|
611
|
+
latents: Optional[torch.Tensor],
|
612
|
+
generator: Optional[torch.Generator],
|
613
|
+
ensemble_size: int,
|
614
|
+
batch_size: int,
|
615
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
616
|
+
def retrieve_latents(encoder_output):
|
617
|
+
if hasattr(encoder_output, "latent_dist"):
|
618
|
+
return encoder_output.latent_dist.mode()
|
619
|
+
elif hasattr(encoder_output, "latents"):
|
620
|
+
return encoder_output.latents
|
621
|
+
else:
|
622
|
+
raise AttributeError("Could not access latents of provided encoder_output")
|
623
|
+
|
624
|
+
image_latent = torch.cat(
|
625
|
+
[
|
626
|
+
retrieve_latents(self.vae.encode(image[i : i + batch_size]))
|
627
|
+
for i in range(0, image.shape[0], batch_size)
|
628
|
+
],
|
629
|
+
dim=0,
|
630
|
+
) # [N,4,h,w]
|
631
|
+
image_latent = image_latent * self.vae.config.scaling_factor
|
632
|
+
image_latent = image_latent.repeat_interleave(ensemble_size, dim=0) # [N*E,4,h,w]
|
633
|
+
|
634
|
+
pred_latent = latents
|
635
|
+
if pred_latent is None:
|
636
|
+
pred_latent = randn_tensor(
|
637
|
+
image_latent.shape,
|
638
|
+
generator=generator,
|
639
|
+
device=image_latent.device,
|
640
|
+
dtype=image_latent.dtype,
|
641
|
+
) # [N*E,4,h,w]
|
642
|
+
|
643
|
+
return image_latent, pred_latent
|
644
|
+
|
645
|
+
def decode_prediction(self, pred_latent: torch.Tensor) -> torch.Tensor:
|
646
|
+
if pred_latent.dim() != 4 or pred_latent.shape[1] != self.vae.config.latent_channels:
|
647
|
+
raise ValueError(
|
648
|
+
f"Expecting 4D tensor of shape [B,{self.vae.config.latent_channels},H,W]; got {pred_latent.shape}."
|
649
|
+
)
|
650
|
+
|
651
|
+
prediction = self.vae.decode(pred_latent / self.vae.config.scaling_factor, return_dict=False)[0] # [B,3,H,W]
|
652
|
+
|
653
|
+
prediction = prediction.mean(dim=1, keepdim=True) # [B,1,H,W]
|
654
|
+
prediction = torch.clip(prediction, -1.0, 1.0) # [B,1,H,W]
|
655
|
+
prediction = (prediction + 1.0) / 2.0
|
656
|
+
|
657
|
+
return prediction # [B,1,H,W]
|
658
|
+
|
659
|
+
@staticmethod
|
660
|
+
def ensemble_depth(
|
661
|
+
depth: torch.Tensor,
|
662
|
+
scale_invariant: bool = True,
|
663
|
+
shift_invariant: bool = True,
|
664
|
+
output_uncertainty: bool = False,
|
665
|
+
reduction: str = "median",
|
666
|
+
regularizer_strength: float = 0.02,
|
667
|
+
max_iter: int = 2,
|
668
|
+
tol: float = 1e-3,
|
669
|
+
max_res: int = 1024,
|
670
|
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
671
|
+
"""
|
672
|
+
Ensembles the depth maps represented by the `depth` tensor with expected shape `(B, 1, H, W)`, where B is the
|
673
|
+
number of ensemble members for a given prediction of size `(H x W)`. Even though the function is designed for
|
674
|
+
depth maps, it can also be used with disparity maps as long as the input tensor values are non-negative. The
|
675
|
+
alignment happens when the predictions have one or more degrees of freedom, that is when they are either
|
676
|
+
affine-invariant (`scale_invariant=True` and `shift_invariant=True`), or just scale-invariant (only
|
677
|
+
`scale_invariant=True`). For absolute predictions (`scale_invariant=False` and `shift_invariant=False`)
|
678
|
+
alignment is skipped and only ensembling is performed.
|
679
|
+
|
680
|
+
Args:
|
681
|
+
depth (`torch.Tensor`):
|
682
|
+
Input ensemble depth maps.
|
683
|
+
scale_invariant (`bool`, *optional*, defaults to `True`):
|
684
|
+
Whether to treat predictions as scale-invariant.
|
685
|
+
shift_invariant (`bool`, *optional*, defaults to `True`):
|
686
|
+
Whether to treat predictions as shift-invariant.
|
687
|
+
output_uncertainty (`bool`, *optional*, defaults to `False`):
|
688
|
+
Whether to output uncertainty map.
|
689
|
+
reduction (`str`, *optional*, defaults to `"median"`):
|
690
|
+
Reduction method used to ensemble aligned predictions. The accepted values are: `"mean"` and
|
691
|
+
`"median"`.
|
692
|
+
regularizer_strength (`float`, *optional*, defaults to `0.02`):
|
693
|
+
Strength of the regularizer that pulls the aligned predictions to the unit range from 0 to 1.
|
694
|
+
max_iter (`int`, *optional*, defaults to `2`):
|
695
|
+
Maximum number of the alignment solver steps. Refer to `scipy.optimize.minimize` function, `options`
|
696
|
+
argument.
|
697
|
+
tol (`float`, *optional*, defaults to `1e-3`):
|
698
|
+
Alignment solver tolerance. The solver stops when the tolerance is reached.
|
699
|
+
max_res (`int`, *optional*, defaults to `1024`):
|
700
|
+
Resolution at which the alignment is performed; `None` matches the `processing_resolution`.
|
701
|
+
Returns:
|
702
|
+
A tensor of aligned and ensembled depth maps and optionally a tensor of uncertainties of the same shape:
|
703
|
+
`(1, 1, H, W)`.
|
704
|
+
"""
|
705
|
+
if depth.dim() != 4 or depth.shape[1] != 1:
|
706
|
+
raise ValueError(f"Expecting 4D tensor of shape [B,1,H,W]; got {depth.shape}.")
|
707
|
+
if reduction not in ("mean", "median"):
|
708
|
+
raise ValueError(f"Unrecognized reduction method: {reduction}.")
|
709
|
+
if not scale_invariant and shift_invariant:
|
710
|
+
raise ValueError("Pure shift-invariant ensembling is not supported.")
|
711
|
+
|
712
|
+
def init_param(depth: torch.Tensor):
|
713
|
+
init_min = depth.reshape(ensemble_size, -1).min(dim=1).values
|
714
|
+
init_max = depth.reshape(ensemble_size, -1).max(dim=1).values
|
715
|
+
|
716
|
+
if scale_invariant and shift_invariant:
|
717
|
+
init_s = 1.0 / (init_max - init_min).clamp(min=1e-6)
|
718
|
+
init_t = -init_s * init_min
|
719
|
+
param = torch.cat((init_s, init_t)).cpu().numpy()
|
720
|
+
elif scale_invariant:
|
721
|
+
init_s = 1.0 / init_max.clamp(min=1e-6)
|
722
|
+
param = init_s.cpu().numpy()
|
723
|
+
else:
|
724
|
+
raise ValueError("Unrecognized alignment.")
|
725
|
+
|
726
|
+
return param
|
727
|
+
|
728
|
+
def align(depth: torch.Tensor, param: np.ndarray) -> torch.Tensor:
|
729
|
+
if scale_invariant and shift_invariant:
|
730
|
+
s, t = np.split(param, 2)
|
731
|
+
s = torch.from_numpy(s).to(depth).view(ensemble_size, 1, 1, 1)
|
732
|
+
t = torch.from_numpy(t).to(depth).view(ensemble_size, 1, 1, 1)
|
733
|
+
out = depth * s + t
|
734
|
+
elif scale_invariant:
|
735
|
+
s = torch.from_numpy(param).to(depth).view(ensemble_size, 1, 1, 1)
|
736
|
+
out = depth * s
|
737
|
+
else:
|
738
|
+
raise ValueError("Unrecognized alignment.")
|
739
|
+
return out
|
740
|
+
|
741
|
+
def ensemble(
|
742
|
+
depth_aligned: torch.Tensor, return_uncertainty: bool = False
|
743
|
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
744
|
+
uncertainty = None
|
745
|
+
if reduction == "mean":
|
746
|
+
prediction = torch.mean(depth_aligned, dim=0, keepdim=True)
|
747
|
+
if return_uncertainty:
|
748
|
+
uncertainty = torch.std(depth_aligned, dim=0, keepdim=True)
|
749
|
+
elif reduction == "median":
|
750
|
+
prediction = torch.median(depth_aligned, dim=0, keepdim=True).values
|
751
|
+
if return_uncertainty:
|
752
|
+
uncertainty = torch.median(torch.abs(depth_aligned - prediction), dim=0, keepdim=True).values
|
753
|
+
else:
|
754
|
+
raise ValueError(f"Unrecognized reduction method: {reduction}.")
|
755
|
+
return prediction, uncertainty
|
756
|
+
|
757
|
+
def cost_fn(param: np.ndarray, depth: torch.Tensor) -> float:
|
758
|
+
cost = 0.0
|
759
|
+
depth_aligned = align(depth, param)
|
760
|
+
|
761
|
+
for i, j in torch.combinations(torch.arange(ensemble_size)):
|
762
|
+
diff = depth_aligned[i] - depth_aligned[j]
|
763
|
+
cost += (diff**2).mean().sqrt().item()
|
764
|
+
|
765
|
+
if regularizer_strength > 0:
|
766
|
+
prediction, _ = ensemble(depth_aligned, return_uncertainty=False)
|
767
|
+
err_near = (0.0 - prediction.min()).abs().item()
|
768
|
+
err_far = (1.0 - prediction.max()).abs().item()
|
769
|
+
cost += (err_near + err_far) * regularizer_strength
|
770
|
+
|
771
|
+
return cost
|
772
|
+
|
773
|
+
def compute_param(depth: torch.Tensor):
|
774
|
+
import scipy
|
775
|
+
|
776
|
+
depth_to_align = depth.to(torch.float32)
|
777
|
+
if max_res is not None and max(depth_to_align.shape[2:]) > max_res:
|
778
|
+
depth_to_align = MarigoldImageProcessor.resize_to_max_edge(depth_to_align, max_res, "nearest-exact")
|
779
|
+
|
780
|
+
param = init_param(depth_to_align)
|
781
|
+
|
782
|
+
res = scipy.optimize.minimize(
|
783
|
+
partial(cost_fn, depth=depth_to_align),
|
784
|
+
param,
|
785
|
+
method="BFGS",
|
786
|
+
tol=tol,
|
787
|
+
options={"maxiter": max_iter, "disp": False},
|
788
|
+
)
|
789
|
+
|
790
|
+
return res.x
|
791
|
+
|
792
|
+
requires_aligning = scale_invariant or shift_invariant
|
793
|
+
ensemble_size = depth.shape[0]
|
794
|
+
|
795
|
+
if requires_aligning:
|
796
|
+
param = compute_param(depth)
|
797
|
+
depth = align(depth, param)
|
798
|
+
|
799
|
+
depth, uncertainty = ensemble(depth, return_uncertainty=output_uncertainty)
|
800
|
+
|
801
|
+
depth_max = depth.max()
|
802
|
+
if scale_invariant and shift_invariant:
|
803
|
+
depth_min = depth.min()
|
804
|
+
elif scale_invariant:
|
805
|
+
depth_min = 0
|
806
|
+
else:
|
807
|
+
raise ValueError("Unrecognized alignment.")
|
808
|
+
depth_range = (depth_max - depth_min).clamp(min=1e-6)
|
809
|
+
depth = (depth - depth_min) / depth_range
|
810
|
+
if output_uncertainty:
|
811
|
+
uncertainty /= depth_range
|
812
|
+
|
813
|
+
return depth, uncertainty # [1,1,H,W], [1,1,H,W]
|