diffusers 0.27.1__py3-none-any.whl → 0.28.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.
Files changed (270) hide show
  1. diffusers/__init__.py +18 -1
  2. diffusers/callbacks.py +156 -0
  3. diffusers/commands/env.py +110 -6
  4. diffusers/configuration_utils.py +16 -11
  5. diffusers/dependency_versions_table.py +2 -1
  6. diffusers/image_processor.py +158 -45
  7. diffusers/loaders/__init__.py +2 -5
  8. diffusers/loaders/autoencoder.py +4 -4
  9. diffusers/loaders/controlnet.py +4 -4
  10. diffusers/loaders/ip_adapter.py +80 -22
  11. diffusers/loaders/lora.py +134 -20
  12. diffusers/loaders/lora_conversion_utils.py +46 -43
  13. diffusers/loaders/peft.py +4 -3
  14. diffusers/loaders/single_file.py +401 -170
  15. diffusers/loaders/single_file_model.py +290 -0
  16. diffusers/loaders/single_file_utils.py +616 -672
  17. diffusers/loaders/textual_inversion.py +41 -20
  18. diffusers/loaders/unet.py +168 -115
  19. diffusers/loaders/unet_loader_utils.py +163 -0
  20. diffusers/models/__init__.py +2 -0
  21. diffusers/models/activations.py +11 -3
  22. diffusers/models/attention.py +10 -11
  23. diffusers/models/attention_processor.py +367 -148
  24. diffusers/models/autoencoders/autoencoder_asym_kl.py +14 -16
  25. diffusers/models/autoencoders/autoencoder_kl.py +18 -19
  26. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +11 -11
  27. diffusers/models/autoencoders/autoencoder_tiny.py +16 -16
  28. diffusers/models/autoencoders/consistency_decoder_vae.py +36 -11
  29. diffusers/models/autoencoders/vae.py +23 -24
  30. diffusers/models/controlnet.py +12 -9
  31. diffusers/models/controlnet_flax.py +4 -4
  32. diffusers/models/controlnet_xs.py +1915 -0
  33. diffusers/models/downsampling.py +17 -18
  34. diffusers/models/embeddings.py +147 -24
  35. diffusers/models/model_loading_utils.py +149 -0
  36. diffusers/models/modeling_flax_pytorch_utils.py +2 -1
  37. diffusers/models/modeling_flax_utils.py +4 -4
  38. diffusers/models/modeling_pytorch_flax_utils.py +1 -1
  39. diffusers/models/modeling_utils.py +118 -98
  40. diffusers/models/resnet.py +18 -23
  41. diffusers/models/transformer_temporal.py +3 -3
  42. diffusers/models/transformers/dual_transformer_2d.py +4 -4
  43. diffusers/models/transformers/prior_transformer.py +7 -7
  44. diffusers/models/transformers/t5_film_transformer.py +17 -19
  45. diffusers/models/transformers/transformer_2d.py +272 -156
  46. diffusers/models/transformers/transformer_temporal.py +10 -10
  47. diffusers/models/unets/unet_1d.py +5 -5
  48. diffusers/models/unets/unet_1d_blocks.py +29 -29
  49. diffusers/models/unets/unet_2d.py +6 -6
  50. diffusers/models/unets/unet_2d_blocks.py +137 -128
  51. diffusers/models/unets/unet_2d_condition.py +20 -15
  52. diffusers/models/unets/unet_2d_condition_flax.py +6 -5
  53. diffusers/models/unets/unet_3d_blocks.py +79 -77
  54. diffusers/models/unets/unet_3d_condition.py +13 -9
  55. diffusers/models/unets/unet_i2vgen_xl.py +14 -13
  56. diffusers/models/unets/unet_kandinsky3.py +1 -1
  57. diffusers/models/unets/unet_motion_model.py +114 -14
  58. diffusers/models/unets/unet_spatio_temporal_condition.py +15 -14
  59. diffusers/models/unets/unet_stable_cascade.py +16 -13
  60. diffusers/models/upsampling.py +17 -20
  61. diffusers/models/vq_model.py +16 -15
  62. diffusers/pipelines/__init__.py +25 -3
  63. diffusers/pipelines/amused/pipeline_amused.py +12 -12
  64. diffusers/pipelines/amused/pipeline_amused_img2img.py +14 -12
  65. diffusers/pipelines/amused/pipeline_amused_inpaint.py +13 -11
  66. diffusers/pipelines/animatediff/__init__.py +2 -0
  67. diffusers/pipelines/animatediff/pipeline_animatediff.py +24 -46
  68. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +1284 -0
  69. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +82 -72
  70. diffusers/pipelines/animatediff/pipeline_output.py +3 -2
  71. diffusers/pipelines/audioldm/pipeline_audioldm.py +14 -14
  72. diffusers/pipelines/audioldm2/modeling_audioldm2.py +54 -35
  73. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +120 -36
  74. diffusers/pipelines/auto_pipeline.py +21 -17
  75. diffusers/pipelines/blip_diffusion/blip_image_processing.py +1 -1
  76. diffusers/pipelines/blip_diffusion/modeling_blip2.py +5 -5
  77. diffusers/pipelines/blip_diffusion/modeling_ctx_clip.py +1 -1
  78. diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +2 -2
  79. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +5 -5
  80. diffusers/pipelines/controlnet/multicontrolnet.py +4 -8
  81. diffusers/pipelines/controlnet/pipeline_controlnet.py +87 -52
  82. diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +2 -2
  83. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +50 -43
  84. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +52 -40
  85. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +80 -47
  86. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +147 -49
  87. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +89 -55
  88. diffusers/pipelines/controlnet_xs/__init__.py +68 -0
  89. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +911 -0
  90. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +1115 -0
  91. diffusers/pipelines/deepfloyd_if/pipeline_if.py +14 -28
  92. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +18 -33
  93. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +21 -39
  94. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +20 -36
  95. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +23 -39
  96. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +17 -32
  97. diffusers/pipelines/deprecated/alt_diffusion/modeling_roberta_series.py +11 -11
  98. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +43 -20
  99. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +36 -18
  100. diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +2 -2
  101. diffusers/pipelines/deprecated/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +7 -7
  102. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +12 -12
  103. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +18 -21
  104. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +20 -15
  105. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +20 -15
  106. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +30 -25
  107. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +69 -59
  108. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py +13 -13
  109. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +10 -5
  110. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +11 -6
  111. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +10 -5
  112. diffusers/pipelines/deprecated/vq_diffusion/pipeline_vq_diffusion.py +5 -5
  113. diffusers/pipelines/dit/pipeline_dit.py +3 -0
  114. diffusers/pipelines/free_init_utils.py +39 -38
  115. diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +33 -48
  116. diffusers/pipelines/kandinsky/pipeline_kandinsky.py +8 -8
  117. diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +23 -20
  118. diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +11 -11
  119. diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +12 -12
  120. diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +10 -10
  121. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +6 -6
  122. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +32 -29
  123. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +10 -10
  124. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +10 -10
  125. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +6 -6
  126. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +8 -8
  127. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +7 -7
  128. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +6 -6
  129. diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.py +3 -3
  130. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +20 -33
  131. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +24 -35
  132. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +48 -30
  133. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +50 -28
  134. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +11 -11
  135. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +61 -67
  136. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +70 -69
  137. diffusers/pipelines/ledits_pp/pipeline_output.py +2 -2
  138. diffusers/pipelines/marigold/__init__.py +50 -0
  139. diffusers/pipelines/marigold/marigold_image_processing.py +561 -0
  140. diffusers/pipelines/marigold/pipeline_marigold_depth.py +813 -0
  141. diffusers/pipelines/marigold/pipeline_marigold_normals.py +690 -0
  142. diffusers/pipelines/musicldm/pipeline_musicldm.py +14 -14
  143. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +17 -12
  144. diffusers/pipelines/pia/pipeline_pia.py +39 -125
  145. diffusers/pipelines/pipeline_flax_utils.py +4 -4
  146. diffusers/pipelines/pipeline_loading_utils.py +268 -23
  147. diffusers/pipelines/pipeline_utils.py +266 -37
  148. diffusers/pipelines/pixart_alpha/__init__.py +8 -1
  149. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +65 -75
  150. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +880 -0
  151. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +10 -5
  152. diffusers/pipelines/shap_e/pipeline_shap_e.py +3 -3
  153. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +14 -14
  154. diffusers/pipelines/shap_e/renderer.py +1 -1
  155. diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +36 -22
  156. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +23 -19
  157. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +33 -32
  158. diffusers/pipelines/stable_diffusion/__init__.py +0 -1
  159. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +18 -11
  160. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +2 -2
  161. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +6 -6
  162. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +73 -39
  163. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +24 -17
  164. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +13 -8
  165. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +66 -36
  166. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +82 -46
  167. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +123 -28
  168. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +6 -6
  169. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +16 -16
  170. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +24 -19
  171. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +37 -31
  172. diffusers/pipelines/stable_diffusion/safety_checker.py +2 -1
  173. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +23 -15
  174. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +44 -42
  175. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +23 -18
  176. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +19 -14
  177. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +20 -15
  178. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +24 -19
  179. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +65 -32
  180. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +274 -38
  181. diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +10 -5
  182. diffusers/pipelines/stable_diffusion_safe/safety_checker.py +1 -1
  183. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +92 -25
  184. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +88 -44
  185. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +108 -56
  186. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +96 -51
  187. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +45 -25
  188. diffusers/pipelines/stable_diffusion_xl/watermark.py +9 -3
  189. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +110 -57
  190. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +59 -30
  191. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +71 -42
  192. diffusers/pipelines/text_to_video_synthesis/pipeline_output.py +3 -2
  193. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +18 -41
  194. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +21 -85
  195. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +28 -19
  196. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +39 -33
  197. diffusers/pipelines/unclip/pipeline_unclip.py +6 -6
  198. diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +6 -6
  199. diffusers/pipelines/unidiffuser/modeling_text_decoder.py +1 -1
  200. diffusers/pipelines/unidiffuser/modeling_uvit.py +9 -9
  201. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +23 -23
  202. diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +5 -5
  203. diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +5 -10
  204. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +4 -6
  205. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +4 -4
  206. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +12 -12
  207. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +10 -10
  208. diffusers/schedulers/__init__.py +2 -2
  209. diffusers/schedulers/deprecated/__init__.py +1 -1
  210. diffusers/schedulers/deprecated/scheduling_karras_ve.py +25 -25
  211. diffusers/schedulers/scheduling_amused.py +5 -5
  212. diffusers/schedulers/scheduling_consistency_decoder.py +11 -11
  213. diffusers/schedulers/scheduling_consistency_models.py +23 -25
  214. diffusers/schedulers/scheduling_ddim.py +22 -24
  215. diffusers/schedulers/scheduling_ddim_flax.py +2 -1
  216. diffusers/schedulers/scheduling_ddim_inverse.py +16 -16
  217. diffusers/schedulers/scheduling_ddim_parallel.py +28 -30
  218. diffusers/schedulers/scheduling_ddpm.py +20 -22
  219. diffusers/schedulers/scheduling_ddpm_flax.py +7 -3
  220. diffusers/schedulers/scheduling_ddpm_parallel.py +26 -28
  221. diffusers/schedulers/scheduling_ddpm_wuerstchen.py +14 -14
  222. diffusers/schedulers/scheduling_deis_multistep.py +46 -42
  223. diffusers/schedulers/scheduling_dpmsolver_multistep.py +107 -77
  224. diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py +2 -2
  225. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +46 -46
  226. diffusers/schedulers/scheduling_dpmsolver_sde.py +26 -22
  227. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +90 -65
  228. diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +78 -53
  229. diffusers/schedulers/scheduling_edm_euler.py +53 -30
  230. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +26 -28
  231. diffusers/schedulers/scheduling_euler_discrete.py +163 -67
  232. diffusers/schedulers/scheduling_heun_discrete.py +60 -38
  233. diffusers/schedulers/scheduling_ipndm.py +8 -8
  234. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +22 -18
  235. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +22 -18
  236. diffusers/schedulers/scheduling_karras_ve_flax.py +6 -6
  237. diffusers/schedulers/scheduling_lcm.py +21 -23
  238. diffusers/schedulers/scheduling_lms_discrete.py +27 -25
  239. diffusers/schedulers/scheduling_pndm.py +20 -20
  240. diffusers/schedulers/scheduling_repaint.py +20 -20
  241. diffusers/schedulers/scheduling_sasolver.py +55 -54
  242. diffusers/schedulers/scheduling_sde_ve.py +19 -19
  243. diffusers/schedulers/scheduling_tcd.py +39 -30
  244. diffusers/schedulers/scheduling_unclip.py +15 -15
  245. diffusers/schedulers/scheduling_unipc_multistep.py +115 -41
  246. diffusers/schedulers/scheduling_utils.py +14 -5
  247. diffusers/schedulers/scheduling_utils_flax.py +3 -3
  248. diffusers/schedulers/scheduling_vq_diffusion.py +10 -10
  249. diffusers/training_utils.py +56 -1
  250. diffusers/utils/__init__.py +7 -0
  251. diffusers/utils/doc_utils.py +1 -0
  252. diffusers/utils/dummy_pt_objects.py +30 -0
  253. diffusers/utils/dummy_torch_and_transformers_objects.py +90 -0
  254. diffusers/utils/dynamic_modules_utils.py +24 -11
  255. diffusers/utils/hub_utils.py +3 -2
  256. diffusers/utils/import_utils.py +91 -0
  257. diffusers/utils/loading_utils.py +2 -2
  258. diffusers/utils/logging.py +1 -1
  259. diffusers/utils/peft_utils.py +32 -5
  260. diffusers/utils/state_dict_utils.py +11 -2
  261. diffusers/utils/testing_utils.py +71 -6
  262. diffusers/utils/torch_utils.py +1 -0
  263. diffusers/video_processor.py +113 -0
  264. {diffusers-0.27.1.dist-info → diffusers-0.28.0.dist-info}/METADATA +7 -7
  265. diffusers-0.28.0.dist-info/RECORD +414 -0
  266. diffusers-0.27.1.dist-info/RECORD +0 -399
  267. {diffusers-0.27.1.dist-info → diffusers-0.28.0.dist-info}/LICENSE +0 -0
  268. {diffusers-0.27.1.dist-info → diffusers-0.28.0.dist-info}/WHEEL +0 -0
  269. {diffusers-0.27.1.dist-info → diffusers-0.28.0.dist-info}/entry_points.txt +0 -0
  270. {diffusers-0.27.1.dist-info → diffusers-0.28.0.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]