diffusers 0.32.1__py3-none-any.whl → 0.33.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 (389) hide show
  1. diffusers/__init__.py +186 -3
  2. diffusers/configuration_utils.py +40 -12
  3. diffusers/dependency_versions_table.py +9 -2
  4. diffusers/hooks/__init__.py +9 -0
  5. diffusers/hooks/faster_cache.py +653 -0
  6. diffusers/hooks/group_offloading.py +793 -0
  7. diffusers/hooks/hooks.py +236 -0
  8. diffusers/hooks/layerwise_casting.py +245 -0
  9. diffusers/hooks/pyramid_attention_broadcast.py +311 -0
  10. diffusers/loaders/__init__.py +6 -0
  11. diffusers/loaders/ip_adapter.py +38 -30
  12. diffusers/loaders/lora_base.py +198 -28
  13. diffusers/loaders/lora_conversion_utils.py +679 -44
  14. diffusers/loaders/lora_pipeline.py +1963 -801
  15. diffusers/loaders/peft.py +169 -84
  16. diffusers/loaders/single_file.py +17 -2
  17. diffusers/loaders/single_file_model.py +53 -5
  18. diffusers/loaders/single_file_utils.py +653 -75
  19. diffusers/loaders/textual_inversion.py +9 -9
  20. diffusers/loaders/transformer_flux.py +8 -9
  21. diffusers/loaders/transformer_sd3.py +120 -39
  22. diffusers/loaders/unet.py +22 -32
  23. diffusers/models/__init__.py +22 -0
  24. diffusers/models/activations.py +9 -9
  25. diffusers/models/attention.py +0 -1
  26. diffusers/models/attention_processor.py +163 -25
  27. diffusers/models/auto_model.py +169 -0
  28. diffusers/models/autoencoders/__init__.py +2 -0
  29. diffusers/models/autoencoders/autoencoder_asym_kl.py +2 -0
  30. diffusers/models/autoencoders/autoencoder_dc.py +106 -4
  31. diffusers/models/autoencoders/autoencoder_kl.py +0 -4
  32. diffusers/models/autoencoders/autoencoder_kl_allegro.py +5 -23
  33. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +17 -55
  34. diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py +17 -97
  35. diffusers/models/autoencoders/autoencoder_kl_ltx.py +326 -107
  36. diffusers/models/autoencoders/autoencoder_kl_magvit.py +1094 -0
  37. diffusers/models/autoencoders/autoencoder_kl_mochi.py +21 -56
  38. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +11 -42
  39. diffusers/models/autoencoders/autoencoder_kl_wan.py +855 -0
  40. diffusers/models/autoencoders/autoencoder_oobleck.py +1 -0
  41. diffusers/models/autoencoders/autoencoder_tiny.py +0 -4
  42. diffusers/models/autoencoders/consistency_decoder_vae.py +3 -1
  43. diffusers/models/autoencoders/vae.py +31 -141
  44. diffusers/models/autoencoders/vq_model.py +3 -0
  45. diffusers/models/cache_utils.py +108 -0
  46. diffusers/models/controlnets/__init__.py +1 -0
  47. diffusers/models/controlnets/controlnet.py +3 -8
  48. diffusers/models/controlnets/controlnet_flux.py +14 -42
  49. diffusers/models/controlnets/controlnet_sd3.py +58 -34
  50. diffusers/models/controlnets/controlnet_sparsectrl.py +4 -7
  51. diffusers/models/controlnets/controlnet_union.py +27 -18
  52. diffusers/models/controlnets/controlnet_xs.py +7 -46
  53. diffusers/models/controlnets/multicontrolnet_union.py +196 -0
  54. diffusers/models/embeddings.py +18 -7
  55. diffusers/models/model_loading_utils.py +122 -80
  56. diffusers/models/modeling_flax_pytorch_utils.py +1 -1
  57. diffusers/models/modeling_flax_utils.py +1 -1
  58. diffusers/models/modeling_pytorch_flax_utils.py +1 -1
  59. diffusers/models/modeling_utils.py +617 -272
  60. diffusers/models/normalization.py +67 -14
  61. diffusers/models/resnet.py +1 -1
  62. diffusers/models/transformers/__init__.py +6 -0
  63. diffusers/models/transformers/auraflow_transformer_2d.py +9 -35
  64. diffusers/models/transformers/cogvideox_transformer_3d.py +13 -24
  65. diffusers/models/transformers/consisid_transformer_3d.py +789 -0
  66. diffusers/models/transformers/dit_transformer_2d.py +5 -19
  67. diffusers/models/transformers/hunyuan_transformer_2d.py +4 -3
  68. diffusers/models/transformers/latte_transformer_3d.py +20 -15
  69. diffusers/models/transformers/lumina_nextdit2d.py +3 -1
  70. diffusers/models/transformers/pixart_transformer_2d.py +4 -19
  71. diffusers/models/transformers/prior_transformer.py +5 -1
  72. diffusers/models/transformers/sana_transformer.py +144 -40
  73. diffusers/models/transformers/stable_audio_transformer.py +5 -20
  74. diffusers/models/transformers/transformer_2d.py +7 -22
  75. diffusers/models/transformers/transformer_allegro.py +9 -17
  76. diffusers/models/transformers/transformer_cogview3plus.py +6 -17
  77. diffusers/models/transformers/transformer_cogview4.py +462 -0
  78. diffusers/models/transformers/transformer_easyanimate.py +527 -0
  79. diffusers/models/transformers/transformer_flux.py +68 -110
  80. diffusers/models/transformers/transformer_hunyuan_video.py +409 -49
  81. diffusers/models/transformers/transformer_ltx.py +53 -35
  82. diffusers/models/transformers/transformer_lumina2.py +548 -0
  83. diffusers/models/transformers/transformer_mochi.py +6 -17
  84. diffusers/models/transformers/transformer_omnigen.py +469 -0
  85. diffusers/models/transformers/transformer_sd3.py +56 -86
  86. diffusers/models/transformers/transformer_temporal.py +5 -11
  87. diffusers/models/transformers/transformer_wan.py +469 -0
  88. diffusers/models/unets/unet_1d.py +3 -1
  89. diffusers/models/unets/unet_2d.py +21 -20
  90. diffusers/models/unets/unet_2d_blocks.py +19 -243
  91. diffusers/models/unets/unet_2d_condition.py +4 -6
  92. diffusers/models/unets/unet_3d_blocks.py +14 -127
  93. diffusers/models/unets/unet_3d_condition.py +8 -12
  94. diffusers/models/unets/unet_i2vgen_xl.py +5 -13
  95. diffusers/models/unets/unet_kandinsky3.py +0 -4
  96. diffusers/models/unets/unet_motion_model.py +20 -114
  97. diffusers/models/unets/unet_spatio_temporal_condition.py +7 -8
  98. diffusers/models/unets/unet_stable_cascade.py +8 -35
  99. diffusers/models/unets/uvit_2d.py +1 -4
  100. diffusers/optimization.py +2 -2
  101. diffusers/pipelines/__init__.py +57 -8
  102. diffusers/pipelines/allegro/pipeline_allegro.py +22 -2
  103. diffusers/pipelines/amused/pipeline_amused.py +15 -2
  104. diffusers/pipelines/amused/pipeline_amused_img2img.py +15 -2
  105. diffusers/pipelines/amused/pipeline_amused_inpaint.py +15 -2
  106. diffusers/pipelines/animatediff/pipeline_animatediff.py +15 -2
  107. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +15 -3
  108. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +24 -4
  109. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +15 -2
  110. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +16 -4
  111. diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +16 -4
  112. diffusers/pipelines/audioldm/pipeline_audioldm.py +13 -2
  113. diffusers/pipelines/audioldm2/modeling_audioldm2.py +13 -68
  114. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +39 -9
  115. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +63 -7
  116. diffusers/pipelines/auto_pipeline.py +35 -14
  117. diffusers/pipelines/blip_diffusion/blip_image_processing.py +1 -1
  118. diffusers/pipelines/blip_diffusion/modeling_blip2.py +5 -8
  119. diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +12 -0
  120. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +22 -6
  121. diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +22 -6
  122. diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +22 -5
  123. diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +22 -6
  124. diffusers/pipelines/cogview3/pipeline_cogview3plus.py +12 -4
  125. diffusers/pipelines/cogview4/__init__.py +49 -0
  126. diffusers/pipelines/cogview4/pipeline_cogview4.py +684 -0
  127. diffusers/pipelines/cogview4/pipeline_cogview4_control.py +732 -0
  128. diffusers/pipelines/cogview4/pipeline_output.py +21 -0
  129. diffusers/pipelines/consisid/__init__.py +49 -0
  130. diffusers/pipelines/consisid/consisid_utils.py +357 -0
  131. diffusers/pipelines/consisid/pipeline_consisid.py +974 -0
  132. diffusers/pipelines/consisid/pipeline_output.py +20 -0
  133. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +11 -0
  134. diffusers/pipelines/controlnet/pipeline_controlnet.py +6 -5
  135. diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +13 -0
  136. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +17 -5
  137. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +31 -12
  138. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +26 -7
  139. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +20 -3
  140. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +22 -3
  141. diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +26 -25
  142. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +224 -109
  143. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +25 -29
  144. diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +7 -4
  145. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +3 -5
  146. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +121 -10
  147. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +122 -11
  148. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +12 -1
  149. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +20 -3
  150. diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +14 -2
  151. diffusers/pipelines/ddim/pipeline_ddim.py +14 -1
  152. diffusers/pipelines/ddpm/pipeline_ddpm.py +15 -1
  153. diffusers/pipelines/deepfloyd_if/pipeline_if.py +12 -0
  154. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +12 -0
  155. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +14 -1
  156. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +12 -0
  157. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +14 -1
  158. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +14 -1
  159. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +11 -7
  160. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +11 -7
  161. diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +1 -1
  162. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +10 -6
  163. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_onnx_stable_diffusion_inpaint_legacy.py +2 -2
  164. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +11 -7
  165. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +1 -1
  166. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +1 -1
  167. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +1 -1
  168. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +10 -105
  169. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py +1 -1
  170. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +1 -1
  171. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +1 -1
  172. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +1 -1
  173. diffusers/pipelines/dit/pipeline_dit.py +15 -2
  174. diffusers/pipelines/easyanimate/__init__.py +52 -0
  175. diffusers/pipelines/easyanimate/pipeline_easyanimate.py +770 -0
  176. diffusers/pipelines/easyanimate/pipeline_easyanimate_control.py +994 -0
  177. diffusers/pipelines/easyanimate/pipeline_easyanimate_inpaint.py +1234 -0
  178. diffusers/pipelines/easyanimate/pipeline_output.py +20 -0
  179. diffusers/pipelines/flux/pipeline_flux.py +53 -21
  180. diffusers/pipelines/flux/pipeline_flux_control.py +9 -12
  181. diffusers/pipelines/flux/pipeline_flux_control_img2img.py +6 -10
  182. diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +8 -10
  183. diffusers/pipelines/flux/pipeline_flux_controlnet.py +185 -13
  184. diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +8 -10
  185. diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +16 -16
  186. diffusers/pipelines/flux/pipeline_flux_fill.py +107 -39
  187. diffusers/pipelines/flux/pipeline_flux_img2img.py +193 -15
  188. diffusers/pipelines/flux/pipeline_flux_inpaint.py +199 -19
  189. diffusers/pipelines/free_noise_utils.py +3 -3
  190. diffusers/pipelines/hunyuan_video/__init__.py +4 -0
  191. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_skyreels_image2video.py +804 -0
  192. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +90 -23
  193. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video_image2video.py +924 -0
  194. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +3 -5
  195. diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +13 -1
  196. diffusers/pipelines/kandinsky/pipeline_kandinsky.py +12 -0
  197. diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +1 -1
  198. diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +12 -0
  199. diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +13 -1
  200. diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +12 -0
  201. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +12 -1
  202. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +13 -0
  203. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +12 -0
  204. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +12 -1
  205. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +12 -1
  206. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +12 -0
  207. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +12 -0
  208. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +12 -0
  209. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +12 -0
  210. diffusers/pipelines/kolors/pipeline_kolors.py +10 -8
  211. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +6 -4
  212. diffusers/pipelines/kolors/text_encoder.py +7 -34
  213. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +12 -1
  214. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +13 -1
  215. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +14 -13
  216. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion_superresolution.py +12 -1
  217. diffusers/pipelines/latte/pipeline_latte.py +36 -7
  218. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +67 -13
  219. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +60 -15
  220. diffusers/pipelines/ltx/__init__.py +2 -0
  221. diffusers/pipelines/ltx/pipeline_ltx.py +25 -13
  222. diffusers/pipelines/ltx/pipeline_ltx_condition.py +1194 -0
  223. diffusers/pipelines/ltx/pipeline_ltx_image2video.py +31 -17
  224. diffusers/pipelines/lumina/__init__.py +2 -2
  225. diffusers/pipelines/lumina/pipeline_lumina.py +83 -20
  226. diffusers/pipelines/lumina2/__init__.py +48 -0
  227. diffusers/pipelines/lumina2/pipeline_lumina2.py +790 -0
  228. diffusers/pipelines/marigold/__init__.py +2 -0
  229. diffusers/pipelines/marigold/marigold_image_processing.py +127 -14
  230. diffusers/pipelines/marigold/pipeline_marigold_depth.py +31 -16
  231. diffusers/pipelines/marigold/pipeline_marigold_intrinsics.py +721 -0
  232. diffusers/pipelines/marigold/pipeline_marigold_normals.py +31 -16
  233. diffusers/pipelines/mochi/pipeline_mochi.py +14 -18
  234. diffusers/pipelines/musicldm/pipeline_musicldm.py +16 -1
  235. diffusers/pipelines/omnigen/__init__.py +50 -0
  236. diffusers/pipelines/omnigen/pipeline_omnigen.py +512 -0
  237. diffusers/pipelines/omnigen/processor_omnigen.py +327 -0
  238. diffusers/pipelines/onnx_utils.py +5 -3
  239. diffusers/pipelines/pag/pag_utils.py +1 -1
  240. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +12 -1
  241. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +15 -4
  242. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +20 -3
  243. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +20 -3
  244. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +1 -3
  245. diffusers/pipelines/pag/pipeline_pag_kolors.py +6 -4
  246. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +16 -3
  247. diffusers/pipelines/pag/pipeline_pag_sana.py +65 -8
  248. diffusers/pipelines/pag/pipeline_pag_sd.py +23 -7
  249. diffusers/pipelines/pag/pipeline_pag_sd_3.py +3 -5
  250. diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +3 -5
  251. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +13 -1
  252. diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +23 -7
  253. diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +26 -10
  254. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +12 -4
  255. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +7 -3
  256. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +10 -6
  257. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +13 -3
  258. diffusers/pipelines/pia/pipeline_pia.py +13 -1
  259. diffusers/pipelines/pipeline_flax_utils.py +7 -7
  260. diffusers/pipelines/pipeline_loading_utils.py +193 -83
  261. diffusers/pipelines/pipeline_utils.py +221 -106
  262. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +17 -5
  263. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +17 -4
  264. diffusers/pipelines/sana/__init__.py +2 -0
  265. diffusers/pipelines/sana/pipeline_sana.py +183 -58
  266. diffusers/pipelines/sana/pipeline_sana_sprint.py +889 -0
  267. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +12 -2
  268. diffusers/pipelines/shap_e/pipeline_shap_e.py +12 -0
  269. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +12 -0
  270. diffusers/pipelines/shap_e/renderer.py +6 -6
  271. diffusers/pipelines/stable_audio/pipeline_stable_audio.py +1 -1
  272. diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +15 -4
  273. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +12 -8
  274. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +12 -1
  275. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +3 -2
  276. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +14 -10
  277. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_img2img.py +3 -3
  278. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_inpaint.py +14 -10
  279. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +2 -2
  280. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +4 -3
  281. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +5 -4
  282. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +2 -2
  283. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +18 -13
  284. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +30 -8
  285. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +24 -10
  286. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +28 -12
  287. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +39 -18
  288. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +17 -6
  289. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +13 -3
  290. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +20 -3
  291. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +14 -2
  292. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +13 -1
  293. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +16 -17
  294. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +136 -18
  295. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +150 -21
  296. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +15 -3
  297. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +26 -11
  298. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +15 -3
  299. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +22 -4
  300. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +30 -13
  301. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +12 -4
  302. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +15 -3
  303. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +15 -3
  304. diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +26 -12
  305. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +16 -4
  306. diffusers/pipelines/stable_diffusion_xl/pipeline_flax_stable_diffusion_xl.py +1 -1
  307. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +12 -4
  308. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +7 -3
  309. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +10 -6
  310. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +11 -4
  311. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +13 -2
  312. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +18 -4
  313. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +26 -5
  314. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +13 -1
  315. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +13 -1
  316. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +28 -6
  317. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +26 -4
  318. diffusers/pipelines/transformers_loading_utils.py +121 -0
  319. diffusers/pipelines/unclip/pipeline_unclip.py +11 -1
  320. diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +11 -1
  321. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +19 -2
  322. diffusers/pipelines/wan/__init__.py +51 -0
  323. diffusers/pipelines/wan/pipeline_output.py +20 -0
  324. diffusers/pipelines/wan/pipeline_wan.py +593 -0
  325. diffusers/pipelines/wan/pipeline_wan_i2v.py +722 -0
  326. diffusers/pipelines/wan/pipeline_wan_video2video.py +725 -0
  327. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +7 -31
  328. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +12 -1
  329. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +12 -1
  330. diffusers/quantizers/auto.py +5 -1
  331. diffusers/quantizers/base.py +5 -9
  332. diffusers/quantizers/bitsandbytes/bnb_quantizer.py +41 -29
  333. diffusers/quantizers/bitsandbytes/utils.py +30 -20
  334. diffusers/quantizers/gguf/gguf_quantizer.py +1 -0
  335. diffusers/quantizers/gguf/utils.py +4 -2
  336. diffusers/quantizers/quantization_config.py +59 -4
  337. diffusers/quantizers/quanto/__init__.py +1 -0
  338. diffusers/quantizers/quanto/quanto_quantizer.py +177 -0
  339. diffusers/quantizers/quanto/utils.py +60 -0
  340. diffusers/quantizers/torchao/__init__.py +1 -1
  341. diffusers/quantizers/torchao/torchao_quantizer.py +47 -2
  342. diffusers/schedulers/__init__.py +2 -1
  343. diffusers/schedulers/scheduling_consistency_models.py +1 -2
  344. diffusers/schedulers/scheduling_ddim_inverse.py +1 -1
  345. diffusers/schedulers/scheduling_ddpm.py +2 -3
  346. diffusers/schedulers/scheduling_ddpm_parallel.py +1 -2
  347. diffusers/schedulers/scheduling_dpmsolver_multistep.py +12 -4
  348. diffusers/schedulers/scheduling_edm_euler.py +45 -10
  349. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +116 -28
  350. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +7 -6
  351. diffusers/schedulers/scheduling_heun_discrete.py +1 -1
  352. diffusers/schedulers/scheduling_lcm.py +1 -2
  353. diffusers/schedulers/scheduling_lms_discrete.py +1 -1
  354. diffusers/schedulers/scheduling_repaint.py +5 -1
  355. diffusers/schedulers/scheduling_scm.py +265 -0
  356. diffusers/schedulers/scheduling_tcd.py +1 -2
  357. diffusers/schedulers/scheduling_utils.py +2 -1
  358. diffusers/training_utils.py +14 -7
  359. diffusers/utils/__init__.py +10 -2
  360. diffusers/utils/constants.py +13 -1
  361. diffusers/utils/deprecation_utils.py +1 -1
  362. diffusers/utils/dummy_bitsandbytes_objects.py +17 -0
  363. diffusers/utils/dummy_gguf_objects.py +17 -0
  364. diffusers/utils/dummy_optimum_quanto_objects.py +17 -0
  365. diffusers/utils/dummy_pt_objects.py +233 -0
  366. diffusers/utils/dummy_torch_and_transformers_and_opencv_objects.py +17 -0
  367. diffusers/utils/dummy_torch_and_transformers_objects.py +270 -0
  368. diffusers/utils/dummy_torchao_objects.py +17 -0
  369. diffusers/utils/dynamic_modules_utils.py +1 -1
  370. diffusers/utils/export_utils.py +28 -3
  371. diffusers/utils/hub_utils.py +52 -102
  372. diffusers/utils/import_utils.py +121 -221
  373. diffusers/utils/loading_utils.py +14 -1
  374. diffusers/utils/logging.py +1 -2
  375. diffusers/utils/peft_utils.py +6 -14
  376. diffusers/utils/remote_utils.py +425 -0
  377. diffusers/utils/source_code_parsing_utils.py +52 -0
  378. diffusers/utils/state_dict_utils.py +15 -1
  379. diffusers/utils/testing_utils.py +243 -13
  380. diffusers/utils/torch_utils.py +10 -0
  381. diffusers/utils/typing_utils.py +91 -0
  382. diffusers/video_processor.py +1 -1
  383. {diffusers-0.32.1.dist-info → diffusers-0.33.0.dist-info}/METADATA +76 -44
  384. diffusers-0.33.0.dist-info/RECORD +608 -0
  385. {diffusers-0.32.1.dist-info → diffusers-0.33.0.dist-info}/WHEEL +1 -1
  386. diffusers-0.32.1.dist-info/RECORD +0 -550
  387. {diffusers-0.32.1.dist-info → diffusers-0.33.0.dist-info}/LICENSE +0 -0
  388. {diffusers-0.32.1.dist-info → diffusers-0.33.0.dist-info}/entry_points.txt +0 -0
  389. {diffusers-0.32.1.dist-info → diffusers-0.33.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,721 @@
1
+ # Copyright 2023-2025 Marigold Team, ETH Zürich. All rights reserved.
2
+ # Copyright 2024-2025 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://marigoldcomputervision.github.io
18
+ # --------------------------------------------------------------------------
19
+ from dataclasses import dataclass
20
+ from typing import Any, Dict, List, Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+ import torch
24
+ from PIL import Image
25
+ from tqdm.auto import tqdm
26
+ from transformers import CLIPTextModel, CLIPTokenizer
27
+
28
+ from ...image_processor import PipelineImageInput
29
+ from ...models import (
30
+ AutoencoderKL,
31
+ UNet2DConditionModel,
32
+ )
33
+ from ...schedulers import (
34
+ DDIMScheduler,
35
+ LCMScheduler,
36
+ )
37
+ from ...utils import (
38
+ BaseOutput,
39
+ is_torch_xla_available,
40
+ logging,
41
+ replace_example_docstring,
42
+ )
43
+ from ...utils.torch_utils import randn_tensor
44
+ from ..pipeline_utils import DiffusionPipeline
45
+ from .marigold_image_processing import MarigoldImageProcessor
46
+
47
+
48
+ if is_torch_xla_available():
49
+ import torch_xla.core.xla_model as xm
50
+
51
+ XLA_AVAILABLE = True
52
+ else:
53
+ XLA_AVAILABLE = False
54
+
55
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
56
+
57
+
58
+ EXAMPLE_DOC_STRING = """
59
+ Examples:
60
+ ```py
61
+ >>> import diffusers
62
+ >>> import torch
63
+
64
+ >>> pipe = diffusers.MarigoldIntrinsicsPipeline.from_pretrained(
65
+ ... "prs-eth/marigold-iid-appearance-v1-1", variant="fp16", torch_dtype=torch.float16
66
+ ... ).to("cuda")
67
+
68
+ >>> image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")
69
+ >>> intrinsics = pipe(image)
70
+
71
+ >>> vis = pipe.image_processor.visualize_intrinsics(intrinsics.prediction, pipe.target_properties)
72
+ >>> vis[0]["albedo"].save("einstein_albedo.png")
73
+ >>> vis[0]["roughness"].save("einstein_roughness.png")
74
+ >>> vis[0]["metallicity"].save("einstein_metallicity.png")
75
+ ```
76
+ ```py
77
+ >>> import diffusers
78
+ >>> import torch
79
+
80
+ >>> pipe = diffusers.MarigoldIntrinsicsPipeline.from_pretrained(
81
+ ... "prs-eth/marigold-iid-lighting-v1-1", variant="fp16", torch_dtype=torch.float16
82
+ ... ).to("cuda")
83
+
84
+ >>> image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")
85
+ >>> intrinsics = pipe(image)
86
+
87
+ >>> vis = pipe.image_processor.visualize_intrinsics(intrinsics.prediction, pipe.target_properties)
88
+ >>> vis[0]["albedo"].save("einstein_albedo.png")
89
+ >>> vis[0]["shading"].save("einstein_shading.png")
90
+ >>> vis[0]["residual"].save("einstein_residual.png")
91
+ ```
92
+ """
93
+
94
+
95
+ @dataclass
96
+ class MarigoldIntrinsicsOutput(BaseOutput):
97
+ """
98
+ Output class for Marigold Intrinsic Image Decomposition pipeline.
99
+
100
+ Args:
101
+ prediction (`np.ndarray`, `torch.Tensor`):
102
+ Predicted image intrinsics with values in the range [0, 1]. The shape is $(numimages * numtargets) \times 3
103
+ \times height \times width$ for `torch.Tensor` or $(numimages * numtargets) \times height \times width
104
+ \times 3$ for `np.ndarray`, where `numtargets` corresponds to the number of predicted target modalities of
105
+ the intrinsic image decomposition.
106
+ uncertainty (`None`, `np.ndarray`, `torch.Tensor`):
107
+ Uncertainty maps computed from the ensemble, with values in the range [0, 1]. The shape is $(numimages *
108
+ numtargets) \times 3 \times height \times width$ for `torch.Tensor` or $(numimages * numtargets) \times
109
+ height \times width \times 3$ for `np.ndarray`.
110
+ latent (`None`, `torch.Tensor`):
111
+ Latent features corresponding to the predictions, compatible with the `latents` argument of the pipeline.
112
+ The shape is $(numimages * numensemble) \times (numtargets * 4) \times latentheight \times latentwidth$.
113
+ """
114
+
115
+ prediction: Union[np.ndarray, torch.Tensor]
116
+ uncertainty: Union[None, np.ndarray, torch.Tensor]
117
+ latent: Union[None, torch.Tensor]
118
+
119
+
120
+ class MarigoldIntrinsicsPipeline(DiffusionPipeline):
121
+ """
122
+ Pipeline for Intrinsic Image Decomposition (IID) using the Marigold method:
123
+ https://marigoldcomputervision.github.io.
124
+
125
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
126
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
127
+
128
+ Args:
129
+ unet (`UNet2DConditionModel`):
130
+ Conditional U-Net to denoise the targets latent, conditioned on image latent.
131
+ vae (`AutoencoderKL`):
132
+ Variational Auto-Encoder (VAE) Model to encode and decode images and predictions to and from latent
133
+ representations.
134
+ scheduler (`DDIMScheduler` or `LCMScheduler`):
135
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents.
136
+ text_encoder (`CLIPTextModel`):
137
+ Text-encoder, for empty text embedding.
138
+ tokenizer (`CLIPTokenizer`):
139
+ CLIP tokenizer.
140
+ prediction_type (`str`, *optional*):
141
+ Type of predictions made by the model.
142
+ target_properties (`Dict[str, Any]`, *optional*):
143
+ Properties of the predicted modalities, such as `target_names`, a `List[str]` used to define the number,
144
+ order and names of the predicted modalities, and any other metadata that may be required to interpret the
145
+ predictions.
146
+ default_denoising_steps (`int`, *optional*):
147
+ The minimum number of denoising diffusion steps that are required to produce a prediction of reasonable
148
+ quality with the given model. This value must be set in the model config. When the pipeline is called
149
+ without explicitly setting `num_inference_steps`, the default value is used. This is required to ensure
150
+ reasonable results with various model flavors compatible with the pipeline, such as those relying on very
151
+ short denoising schedules (`LCMScheduler`) and those with full diffusion schedules (`DDIMScheduler`).
152
+ default_processing_resolution (`int`, *optional*):
153
+ The recommended value of the `processing_resolution` parameter of the pipeline. This value must be set in
154
+ the model config. When the pipeline is called without explicitly setting `processing_resolution`, the
155
+ default value is used. This is required to ensure reasonable results with various model flavors trained
156
+ with varying optimal processing resolution values.
157
+ """
158
+
159
+ model_cpu_offload_seq = "text_encoder->unet->vae"
160
+ supported_prediction_types = ("intrinsics",)
161
+
162
+ def __init__(
163
+ self,
164
+ unet: UNet2DConditionModel,
165
+ vae: AutoencoderKL,
166
+ scheduler: Union[DDIMScheduler, LCMScheduler],
167
+ text_encoder: CLIPTextModel,
168
+ tokenizer: CLIPTokenizer,
169
+ prediction_type: Optional[str] = None,
170
+ target_properties: Optional[Dict[str, Any]] = None,
171
+ default_denoising_steps: Optional[int] = None,
172
+ default_processing_resolution: Optional[int] = None,
173
+ ):
174
+ super().__init__()
175
+
176
+ if prediction_type not in self.supported_prediction_types:
177
+ logger.warning(
178
+ f"Potentially unsupported `prediction_type='{prediction_type}'`; values supported by the pipeline: "
179
+ f"{self.supported_prediction_types}."
180
+ )
181
+
182
+ self.register_modules(
183
+ unet=unet,
184
+ vae=vae,
185
+ scheduler=scheduler,
186
+ text_encoder=text_encoder,
187
+ tokenizer=tokenizer,
188
+ )
189
+ self.register_to_config(
190
+ prediction_type=prediction_type,
191
+ target_properties=target_properties,
192
+ default_denoising_steps=default_denoising_steps,
193
+ default_processing_resolution=default_processing_resolution,
194
+ )
195
+
196
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
197
+
198
+ self.target_properties = target_properties
199
+ self.default_denoising_steps = default_denoising_steps
200
+ self.default_processing_resolution = default_processing_resolution
201
+
202
+ self.empty_text_embedding = None
203
+
204
+ self.image_processor = MarigoldImageProcessor(vae_scale_factor=self.vae_scale_factor)
205
+
206
+ @property
207
+ def n_targets(self):
208
+ return self.unet.config.out_channels // self.vae.config.latent_channels
209
+
210
+ def check_inputs(
211
+ self,
212
+ image: PipelineImageInput,
213
+ num_inference_steps: int,
214
+ ensemble_size: int,
215
+ processing_resolution: int,
216
+ resample_method_input: str,
217
+ resample_method_output: str,
218
+ batch_size: int,
219
+ ensembling_kwargs: Optional[Dict[str, Any]],
220
+ latents: Optional[torch.Tensor],
221
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]],
222
+ output_type: str,
223
+ output_uncertainty: bool,
224
+ ) -> int:
225
+ actual_vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
226
+ if actual_vae_scale_factor != self.vae_scale_factor:
227
+ raise ValueError(
228
+ f"`vae_scale_factor` computed at initialization ({self.vae_scale_factor}) differs from the actual one ({actual_vae_scale_factor})."
229
+ )
230
+ if num_inference_steps is None:
231
+ raise ValueError("`num_inference_steps` is not specified and could not be resolved from the model config.")
232
+ if num_inference_steps < 1:
233
+ raise ValueError("`num_inference_steps` must be positive.")
234
+ if ensemble_size < 1:
235
+ raise ValueError("`ensemble_size` must be positive.")
236
+ if ensemble_size == 2:
237
+ logger.warning(
238
+ "`ensemble_size` == 2 results are similar to no ensembling (1); "
239
+ "consider increasing the value to at least 3."
240
+ )
241
+ if ensemble_size == 1 and output_uncertainty:
242
+ raise ValueError(
243
+ "Computing uncertainty by setting `output_uncertainty=True` also requires setting `ensemble_size` "
244
+ "greater than 1."
245
+ )
246
+ if processing_resolution is None:
247
+ raise ValueError(
248
+ "`processing_resolution` is not specified and could not be resolved from the model config."
249
+ )
250
+ if processing_resolution < 0:
251
+ raise ValueError(
252
+ "`processing_resolution` must be non-negative: 0 for native resolution, or any positive value for "
253
+ "downsampled processing."
254
+ )
255
+ if processing_resolution % self.vae_scale_factor != 0:
256
+ raise ValueError(f"`processing_resolution` must be a multiple of {self.vae_scale_factor}.")
257
+ if resample_method_input not in ("nearest", "nearest-exact", "bilinear", "bicubic", "area"):
258
+ raise ValueError(
259
+ "`resample_method_input` takes string values compatible with PIL library: "
260
+ "nearest, nearest-exact, bilinear, bicubic, area."
261
+ )
262
+ if resample_method_output not in ("nearest", "nearest-exact", "bilinear", "bicubic", "area"):
263
+ raise ValueError(
264
+ "`resample_method_output` takes string values compatible with PIL library: "
265
+ "nearest, nearest-exact, bilinear, bicubic, area."
266
+ )
267
+ if batch_size < 1:
268
+ raise ValueError("`batch_size` must be positive.")
269
+ if output_type not in ["pt", "np"]:
270
+ raise ValueError("`output_type` must be one of `pt` or `np`.")
271
+ if latents is not None and generator is not None:
272
+ raise ValueError("`latents` and `generator` cannot be used together.")
273
+ if ensembling_kwargs is not None:
274
+ if not isinstance(ensembling_kwargs, dict):
275
+ raise ValueError("`ensembling_kwargs` must be a dictionary.")
276
+ if "reduction" in ensembling_kwargs and ensembling_kwargs["reduction"] not in ("median", "mean"):
277
+ raise ValueError("`ensembling_kwargs['reduction']` can be either `'median'` or `'mean'`.")
278
+
279
+ # image checks
280
+ num_images = 0
281
+ W, H = None, None
282
+ if not isinstance(image, list):
283
+ image = [image]
284
+ for i, img in enumerate(image):
285
+ if isinstance(img, np.ndarray) or torch.is_tensor(img):
286
+ if img.ndim not in (2, 3, 4):
287
+ raise ValueError(f"`image[{i}]` has unsupported dimensions or shape: {img.shape}.")
288
+ H_i, W_i = img.shape[-2:]
289
+ N_i = 1
290
+ if img.ndim == 4:
291
+ N_i = img.shape[0]
292
+ elif isinstance(img, Image.Image):
293
+ W_i, H_i = img.size
294
+ N_i = 1
295
+ else:
296
+ raise ValueError(f"Unsupported `image[{i}]` type: {type(img)}.")
297
+ if W is None:
298
+ W, H = W_i, H_i
299
+ elif (W, H) != (W_i, H_i):
300
+ raise ValueError(
301
+ f"Input `image[{i}]` has incompatible dimensions {(W_i, H_i)} with the previous images {(W, H)}"
302
+ )
303
+ num_images += N_i
304
+
305
+ # latents checks
306
+ if latents is not None:
307
+ if not torch.is_tensor(latents):
308
+ raise ValueError("`latents` must be a torch.Tensor.")
309
+ if latents.dim() != 4:
310
+ raise ValueError(f"`latents` has unsupported dimensions or shape: {latents.shape}.")
311
+
312
+ if processing_resolution > 0:
313
+ max_orig = max(H, W)
314
+ new_H = H * processing_resolution // max_orig
315
+ new_W = W * processing_resolution // max_orig
316
+ if new_H == 0 or new_W == 0:
317
+ raise ValueError(f"Extreme aspect ratio of the input image: [{W} x {H}]")
318
+ W, H = new_W, new_H
319
+ w = (W + self.vae_scale_factor - 1) // self.vae_scale_factor
320
+ h = (H + self.vae_scale_factor - 1) // self.vae_scale_factor
321
+ shape_expected = (num_images * ensemble_size, self.unet.config.out_channels, h, w)
322
+
323
+ if latents.shape != shape_expected:
324
+ raise ValueError(f"`latents` has unexpected shape={latents.shape} expected={shape_expected}.")
325
+
326
+ # generator checks
327
+ if generator is not None:
328
+ if isinstance(generator, list):
329
+ if len(generator) != num_images * ensemble_size:
330
+ raise ValueError(
331
+ "The number of generators must match the total number of ensemble members for all input images."
332
+ )
333
+ if not all(g.device.type == generator[0].device.type for g in generator):
334
+ raise ValueError("`generator` device placement is not consistent in the list.")
335
+ elif not isinstance(generator, torch.Generator):
336
+ raise ValueError(f"Unsupported generator type: {type(generator)}.")
337
+
338
+ return num_images
339
+
340
+ @torch.compiler.disable
341
+ def progress_bar(self, iterable=None, total=None, desc=None, leave=True):
342
+ if not hasattr(self, "_progress_bar_config"):
343
+ self._progress_bar_config = {}
344
+ elif not isinstance(self._progress_bar_config, dict):
345
+ raise ValueError(
346
+ f"`self._progress_bar_config` should be of type `dict`, but is {type(self._progress_bar_config)}."
347
+ )
348
+
349
+ progress_bar_config = dict(**self._progress_bar_config)
350
+ progress_bar_config["desc"] = progress_bar_config.get("desc", desc)
351
+ progress_bar_config["leave"] = progress_bar_config.get("leave", leave)
352
+ if iterable is not None:
353
+ return tqdm(iterable, **progress_bar_config)
354
+ elif total is not None:
355
+ return tqdm(total=total, **progress_bar_config)
356
+ else:
357
+ raise ValueError("Either `total` or `iterable` has to be defined.")
358
+
359
+ @torch.no_grad()
360
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
361
+ def __call__(
362
+ self,
363
+ image: PipelineImageInput,
364
+ num_inference_steps: Optional[int] = None,
365
+ ensemble_size: int = 1,
366
+ processing_resolution: Optional[int] = None,
367
+ match_input_resolution: bool = True,
368
+ resample_method_input: str = "bilinear",
369
+ resample_method_output: str = "bilinear",
370
+ batch_size: int = 1,
371
+ ensembling_kwargs: Optional[Dict[str, Any]] = None,
372
+ latents: Optional[Union[torch.Tensor, List[torch.Tensor]]] = None,
373
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
374
+ output_type: str = "np",
375
+ output_uncertainty: bool = False,
376
+ output_latent: bool = False,
377
+ return_dict: bool = True,
378
+ ):
379
+ """
380
+ Function invoked when calling the pipeline.
381
+
382
+ Args:
383
+ image (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`),
384
+ `List[torch.Tensor]`: An input image or images used as an input for the intrinsic decomposition task.
385
+ For arrays and tensors, the expected value range is between `[0, 1]`. Passing a batch of images is
386
+ possible by providing a four-dimensional array or a tensor. Additionally, a list of images of two- or
387
+ three-dimensional arrays or tensors can be passed. In the latter case, all list elements must have the
388
+ same width and height.
389
+ num_inference_steps (`int`, *optional*, defaults to `None`):
390
+ Number of denoising diffusion steps during inference. The default value `None` results in automatic
391
+ selection.
392
+ ensemble_size (`int`, defaults to `1`):
393
+ Number of ensemble predictions. Higher values result in measurable improvements and visual degradation.
394
+ processing_resolution (`int`, *optional*, defaults to `None`):
395
+ Effective processing resolution. When set to `0`, matches the larger input image dimension. This
396
+ produces crisper predictions, but may also lead to the overall loss of global context. The default
397
+ value `None` resolves to the optimal value from the model config.
398
+ match_input_resolution (`bool`, *optional*, defaults to `True`):
399
+ When enabled, the output prediction is resized to match the input dimensions. When disabled, the longer
400
+ side of the output will equal to `processing_resolution`.
401
+ resample_method_input (`str`, *optional*, defaults to `"bilinear"`):
402
+ Resampling method used to resize input images to `processing_resolution`. The accepted values are:
403
+ `"nearest"`, `"nearest-exact"`, `"bilinear"`, `"bicubic"`, or `"area"`.
404
+ resample_method_output (`str`, *optional*, defaults to `"bilinear"`):
405
+ Resampling method used to resize output predictions to match the input resolution. The accepted values
406
+ are `"nearest"`, `"nearest-exact"`, `"bilinear"`, `"bicubic"`, or `"area"`.
407
+ batch_size (`int`, *optional*, defaults to `1`):
408
+ Batch size; only matters when setting `ensemble_size` or passing a tensor of images.
409
+ ensembling_kwargs (`dict`, *optional*, defaults to `None`)
410
+ Extra dictionary with arguments for precise ensembling control. The following options are available:
411
+ - reduction (`str`, *optional*, defaults to `"median"`): Defines the ensembling function applied in
412
+ every pixel location, can be either `"median"` or `"mean"`.
413
+ latents (`torch.Tensor`, *optional*, defaults to `None`):
414
+ Latent noise tensors to replace the random initialization. These can be taken from the previous
415
+ function call's output.
416
+ generator (`torch.Generator`, or `List[torch.Generator]`, *optional*, defaults to `None`):
417
+ Random number generator object to ensure reproducibility.
418
+ output_type (`str`, *optional*, defaults to `"np"`):
419
+ Preferred format of the output's `prediction` and the optional `uncertainty` fields. The accepted
420
+ values are: `"np"` (numpy array) or `"pt"` (torch tensor).
421
+ output_uncertainty (`bool`, *optional*, defaults to `False`):
422
+ When enabled, the output's `uncertainty` field contains the predictive uncertainty map, provided that
423
+ the `ensemble_size` argument is set to a value above 2.
424
+ output_latent (`bool`, *optional*, defaults to `False`):
425
+ When enabled, the output's `latent` field contains the latent codes corresponding to the predictions
426
+ within the ensemble. These codes can be saved, modified, and used for subsequent calls with the
427
+ `latents` argument.
428
+ return_dict (`bool`, *optional*, defaults to `True`):
429
+ Whether or not to return a [`~pipelines.marigold.MarigoldIntrinsicsOutput`] instead of a plain tuple.
430
+
431
+ Examples:
432
+
433
+ Returns:
434
+ [`~pipelines.marigold.MarigoldIntrinsicsOutput`] or `tuple`:
435
+ If `return_dict` is `True`, [`~pipelines.marigold.MarigoldIntrinsicsOutput`] is returned, otherwise a
436
+ `tuple` is returned where the first element is the prediction, the second element is the uncertainty
437
+ (or `None`), and the third is the latent (or `None`).
438
+ """
439
+
440
+ # 0. Resolving variables.
441
+ device = self._execution_device
442
+ dtype = self.dtype
443
+
444
+ # Model-specific optimal default values leading to fast and reasonable results.
445
+ if num_inference_steps is None:
446
+ num_inference_steps = self.default_denoising_steps
447
+ if processing_resolution is None:
448
+ processing_resolution = self.default_processing_resolution
449
+
450
+ # 1. Check inputs.
451
+ num_images = self.check_inputs(
452
+ image,
453
+ num_inference_steps,
454
+ ensemble_size,
455
+ processing_resolution,
456
+ resample_method_input,
457
+ resample_method_output,
458
+ batch_size,
459
+ ensembling_kwargs,
460
+ latents,
461
+ generator,
462
+ output_type,
463
+ output_uncertainty,
464
+ )
465
+
466
+ # 2. Prepare empty text conditioning.
467
+ # Model invocation: self.tokenizer, self.text_encoder.
468
+ if self.empty_text_embedding is None:
469
+ prompt = ""
470
+ text_inputs = self.tokenizer(
471
+ prompt,
472
+ padding="do_not_pad",
473
+ max_length=self.tokenizer.model_max_length,
474
+ truncation=True,
475
+ return_tensors="pt",
476
+ )
477
+ text_input_ids = text_inputs.input_ids.to(device)
478
+ self.empty_text_embedding = self.text_encoder(text_input_ids)[0] # [1,2,1024]
479
+
480
+ # 3. Preprocess input images. This function loads input image or images of compatible dimensions `(H, W)`,
481
+ # optionally downsamples them to the `processing_resolution` `(PH, PW)`, where
482
+ # `max(PH, PW) == processing_resolution`, and pads the dimensions to `(PPH, PPW)` such that these values are
483
+ # divisible by the latent space downscaling factor (typically 8 in Stable Diffusion). The default value `None`
484
+ # of `processing_resolution` resolves to the optimal value from the model config. It is a recommended mode of
485
+ # operation and leads to the most reasonable results. Using the native image resolution or any other processing
486
+ # resolution can lead to loss of either fine details or global context in the output predictions.
487
+ image, padding, original_resolution = self.image_processor.preprocess(
488
+ image, processing_resolution, resample_method_input, device, dtype
489
+ ) # [N,3,PPH,PPW]
490
+
491
+ # 4. Encode input image into latent space. At this step, each of the `N` input images is represented with `E`
492
+ # ensemble members. Each ensemble member is an independent diffused prediction, just initialized independently.
493
+ # Latents of each such predictions across all input images and all ensemble members are represented in the
494
+ # `pred_latent` variable. The variable `image_latent` contains each input image encoded into latent space and
495
+ # replicated `E` times. The variable `pred_latent` contains latents initialization, where the latent space is
496
+ # replicated `T` times relative to the single latent space of `image_latent`, where `T` is the number of the
497
+ # predicted targets. The latents can be either generated (see `generator` to ensure reproducibility), or passed
498
+ # explicitly via the `latents` argument. The latter can be set outside the pipeline code. This behavior can be
499
+ # achieved by setting the `output_latent` argument to `True`. The latent space dimensions are `(h, w)`. Encoding
500
+ # into latent space happens in batches of size `batch_size`.
501
+ # Model invocation: self.vae.encoder.
502
+ image_latent, pred_latent = self.prepare_latents(
503
+ image, latents, generator, ensemble_size, batch_size
504
+ ) # [N*E,4,h,w], [N*E,T*4,h,w]
505
+
506
+ del image
507
+
508
+ batch_empty_text_embedding = self.empty_text_embedding.to(device=device, dtype=dtype).repeat(
509
+ batch_size, 1, 1
510
+ ) # [B,1024,2]
511
+
512
+ # 5. Process the denoising loop. All `N * E` latents are processed sequentially in batches of size `batch_size`.
513
+ # The unet model takes concatenated latent spaces of the input image and the predicted modality as an input, and
514
+ # outputs noise for the predicted modality's latent space. The number of denoising diffusion steps is defined by
515
+ # `num_inference_steps`. It is either set directly, or resolves to the optimal value specific to the loaded
516
+ # model.
517
+ # Model invocation: self.unet.
518
+ pred_latents = []
519
+
520
+ for i in self.progress_bar(
521
+ range(0, num_images * ensemble_size, batch_size), leave=True, desc="Marigold predictions..."
522
+ ):
523
+ batch_image_latent = image_latent[i : i + batch_size] # [B,4,h,w]
524
+ batch_pred_latent = pred_latent[i : i + batch_size] # [B,T*4,h,w]
525
+ effective_batch_size = batch_image_latent.shape[0]
526
+ text = batch_empty_text_embedding[:effective_batch_size] # [B,2,1024]
527
+
528
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
529
+ for t in self.progress_bar(self.scheduler.timesteps, leave=False, desc="Diffusion steps..."):
530
+ batch_latent = torch.cat([batch_image_latent, batch_pred_latent], dim=1) # [B,(1+T)*4,h,w]
531
+ noise = self.unet(batch_latent, t, encoder_hidden_states=text, return_dict=False)[0] # [B,T*4,h,w]
532
+ batch_pred_latent = self.scheduler.step(
533
+ noise, t, batch_pred_latent, generator=generator
534
+ ).prev_sample # [B,T*4,h,w]
535
+
536
+ if XLA_AVAILABLE:
537
+ xm.mark_step()
538
+
539
+ pred_latents.append(batch_pred_latent)
540
+
541
+ pred_latent = torch.cat(pred_latents, dim=0) # [N*E,T*4,h,w]
542
+
543
+ del (
544
+ pred_latents,
545
+ image_latent,
546
+ batch_empty_text_embedding,
547
+ batch_image_latent,
548
+ batch_pred_latent,
549
+ text,
550
+ batch_latent,
551
+ noise,
552
+ )
553
+
554
+ # 6. Decode predictions from latent into pixel space. The resulting `N * E` predictions have shape `(PPH, PPW)`,
555
+ # which requires slight postprocessing. Decoding into pixel space happens in batches of size `batch_size`.
556
+ # Model invocation: self.vae.decoder.
557
+ pred_latent_for_decoding = pred_latent.reshape(
558
+ num_images * ensemble_size * self.n_targets, self.vae.config.latent_channels, *pred_latent.shape[2:]
559
+ ) # [N*E*T,4,PPH,PPW]
560
+ prediction = torch.cat(
561
+ [
562
+ self.decode_prediction(pred_latent_for_decoding[i : i + batch_size])
563
+ for i in range(0, pred_latent_for_decoding.shape[0], batch_size)
564
+ ],
565
+ dim=0,
566
+ ) # [N*E*T,3,PPH,PPW]
567
+
568
+ del pred_latent_for_decoding
569
+ if not output_latent:
570
+ pred_latent = None
571
+
572
+ # 7. Remove padding. The output shape is (PH, PW).
573
+ prediction = self.image_processor.unpad_image(prediction, padding) # [N*E*T,3,PH,PW]
574
+
575
+ # 8. Ensemble and compute uncertainty (when `output_uncertainty` is set). This code treats each of the `N*T`
576
+ # groups of `E` ensemble predictions independently. For each group it computes an ensembled prediction of shape
577
+ # `(PH, PW)` and an optional uncertainty map of the same dimensions. After computing this pair of outputs for
578
+ # each group independently, it stacks them respectively into batches of `N*T` almost final predictions and
579
+ # uncertainty maps.
580
+ uncertainty = None
581
+ if ensemble_size > 1:
582
+ prediction = prediction.reshape(
583
+ num_images, ensemble_size, self.n_targets, *prediction.shape[1:]
584
+ ) # [N,E,T,3,PH,PW]
585
+ prediction = [
586
+ self.ensemble_intrinsics(prediction[i], output_uncertainty, **(ensembling_kwargs or {}))
587
+ for i in range(num_images)
588
+ ] # [ [[T,3,PH,PW], [T,3,PH,PW]], ... ]
589
+ prediction, uncertainty = zip(*prediction) # [[T,3,PH,PW], ... ], [[T,3,PH,PW], ... ]
590
+ prediction = torch.cat(prediction, dim=0) # [N*T,3,PH,PW]
591
+ if output_uncertainty:
592
+ uncertainty = torch.cat(uncertainty, dim=0) # [N*T,3,PH,PW]
593
+ else:
594
+ uncertainty = None
595
+
596
+ # 9. If `match_input_resolution` is set, the output prediction and the uncertainty are upsampled to match the
597
+ # input resolution `(H, W)`. This step may introduce upsampling artifacts, and therefore can be disabled.
598
+ # Depending on the downstream use-case, upsampling can be also chosen based on the tolerated artifacts by
599
+ # setting the `resample_method_output` parameter (e.g., to `"nearest"`).
600
+ if match_input_resolution:
601
+ prediction = self.image_processor.resize_antialias(
602
+ prediction, original_resolution, resample_method_output, is_aa=False
603
+ ) # [N*T,3,H,W]
604
+ if uncertainty is not None and output_uncertainty:
605
+ uncertainty = self.image_processor.resize_antialias(
606
+ uncertainty, original_resolution, resample_method_output, is_aa=False
607
+ ) # [N*T,1,H,W]
608
+
609
+ # 10. Prepare the final outputs.
610
+ if output_type == "np":
611
+ prediction = self.image_processor.pt_to_numpy(prediction) # [N*T,H,W,3]
612
+ if uncertainty is not None and output_uncertainty:
613
+ uncertainty = self.image_processor.pt_to_numpy(uncertainty) # [N*T,H,W,3]
614
+
615
+ # 11. Offload all models
616
+ self.maybe_free_model_hooks()
617
+
618
+ if not return_dict:
619
+ return (prediction, uncertainty, pred_latent)
620
+
621
+ return MarigoldIntrinsicsOutput(
622
+ prediction=prediction,
623
+ uncertainty=uncertainty,
624
+ latent=pred_latent,
625
+ )
626
+
627
+ def prepare_latents(
628
+ self,
629
+ image: torch.Tensor,
630
+ latents: Optional[torch.Tensor],
631
+ generator: Optional[torch.Generator],
632
+ ensemble_size: int,
633
+ batch_size: int,
634
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
635
+ def retrieve_latents(encoder_output):
636
+ if hasattr(encoder_output, "latent_dist"):
637
+ return encoder_output.latent_dist.mode()
638
+ elif hasattr(encoder_output, "latents"):
639
+ return encoder_output.latents
640
+ else:
641
+ raise AttributeError("Could not access latents of provided encoder_output")
642
+
643
+ image_latent = torch.cat(
644
+ [
645
+ retrieve_latents(self.vae.encode(image[i : i + batch_size]))
646
+ for i in range(0, image.shape[0], batch_size)
647
+ ],
648
+ dim=0,
649
+ ) # [N,4,h,w]
650
+ image_latent = image_latent * self.vae.config.scaling_factor
651
+ image_latent = image_latent.repeat_interleave(ensemble_size, dim=0) # [N*E,4,h,w]
652
+ N_E, C, H, W = image_latent.shape
653
+
654
+ pred_latent = latents
655
+ if pred_latent is None:
656
+ pred_latent = randn_tensor(
657
+ (N_E, self.n_targets * C, H, W),
658
+ generator=generator,
659
+ device=image_latent.device,
660
+ dtype=image_latent.dtype,
661
+ ) # [N*E,T*4,h,w]
662
+
663
+ return image_latent, pred_latent
664
+
665
+ def decode_prediction(self, pred_latent: torch.Tensor) -> torch.Tensor:
666
+ if pred_latent.dim() != 4 or pred_latent.shape[1] != self.vae.config.latent_channels:
667
+ raise ValueError(
668
+ f"Expecting 4D tensor of shape [B,{self.vae.config.latent_channels},H,W]; got {pred_latent.shape}."
669
+ )
670
+
671
+ prediction = self.vae.decode(pred_latent / self.vae.config.scaling_factor, return_dict=False)[0] # [B,3,H,W]
672
+
673
+ prediction = torch.clip(prediction, -1.0, 1.0) # [B,3,H,W]
674
+ prediction = (prediction + 1.0) / 2.0
675
+
676
+ return prediction # [B,3,H,W]
677
+
678
+ @staticmethod
679
+ def ensemble_intrinsics(
680
+ targets: torch.Tensor,
681
+ output_uncertainty: bool = False,
682
+ reduction: str = "median",
683
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
684
+ """
685
+ Ensembles the intrinsic decomposition represented by the `targets` tensor with expected shape `(B, T, 3, H,
686
+ W)`, where B is the number of ensemble members for a given prediction of size `(H x W)`, and T is the number of
687
+ predicted targets.
688
+
689
+ Args:
690
+ targets (`torch.Tensor`):
691
+ Input ensemble of intrinsic image decomposition maps.
692
+ output_uncertainty (`bool`, *optional*, defaults to `False`):
693
+ Whether to output uncertainty map.
694
+ reduction (`str`, *optional*, defaults to `"mean"`):
695
+ Reduction method used to ensemble aligned predictions. The accepted values are: `"median"` and
696
+ `"mean"`.
697
+
698
+ Returns:
699
+ A tensor of aligned and ensembled intrinsic decomposition maps with shape `(T, 3, H, W)` and optionally a
700
+ tensor of uncertainties of shape `(T, 3, H, W)`.
701
+ """
702
+ if targets.dim() != 5 or targets.shape[2] != 3:
703
+ raise ValueError(f"Expecting 4D tensor of shape [B,T,3,H,W]; got {targets.shape}.")
704
+ if reduction not in ("median", "mean"):
705
+ raise ValueError(f"Unrecognized reduction method: {reduction}.")
706
+
707
+ B, T, _, H, W = targets.shape
708
+ uncertainty = None
709
+ if reduction == "mean":
710
+ prediction = torch.mean(targets, dim=0) # [T,3,H,W]
711
+ if output_uncertainty:
712
+ uncertainty = torch.std(targets, dim=0) # [T,3,H,W]
713
+ elif reduction == "median":
714
+ prediction = torch.median(targets, dim=0, keepdim=True).values # [1,T,3,H,W]
715
+ if output_uncertainty:
716
+ uncertainty = torch.abs(targets - prediction) # [B,T,3,H,W]
717
+ uncertainty = torch.median(uncertainty, dim=0).values # [T,3,H,W]
718
+ prediction = prediction.squeeze(0) # [T,3,H,W]
719
+ else:
720
+ raise ValueError(f"Unrecognized reduction method: {reduction}.")
721
+ return prediction, uncertainty