diffusers 0.32.2__py3-none-any.whl → 0.33.1__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 +121 -86
  13. diffusers/loaders/lora_conversion_utils.py +504 -44
  14. diffusers/loaders/lora_pipeline.py +1769 -181
  15. diffusers/loaders/peft.py +167 -57
  16. diffusers/loaders/single_file.py +17 -2
  17. diffusers/loaders/single_file_model.py +53 -5
  18. diffusers/loaders/single_file_utils.py +646 -72
  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 +20 -7
  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 +404 -46
  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 +595 -0
  325. diffusers/pipelines/wan/pipeline_wan_i2v.py +724 -0
  326. diffusers/pipelines/wan/pipeline_wan_video2video.py +727 -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 +9 -1
  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 +2 -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.2.dist-info → diffusers-0.33.1.dist-info}/METADATA +21 -4
  384. diffusers-0.33.1.dist-info/RECORD +608 -0
  385. {diffusers-0.32.2.dist-info → diffusers-0.33.1.dist-info}/WHEEL +1 -1
  386. diffusers-0.32.2.dist-info/RECORD +0 -550
  387. {diffusers-0.32.2.dist-info → diffusers-0.33.1.dist-info}/LICENSE +0 -0
  388. {diffusers-0.32.2.dist-info → diffusers-0.33.1.dist-info}/entry_points.txt +0 -0
  389. {diffusers-0.32.2.dist-info → diffusers-0.33.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,724 @@
1
+ # Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import html
16
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
17
+
18
+ import PIL
19
+ import regex as re
20
+ import torch
21
+ from transformers import AutoTokenizer, CLIPImageProcessor, CLIPVisionModel, UMT5EncoderModel
22
+
23
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
24
+ from ...image_processor import PipelineImageInput
25
+ from ...loaders import WanLoraLoaderMixin
26
+ from ...models import AutoencoderKLWan, WanTransformer3DModel
27
+ from ...schedulers import FlowMatchEulerDiscreteScheduler
28
+ from ...utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring
29
+ from ...utils.torch_utils import randn_tensor
30
+ from ...video_processor import VideoProcessor
31
+ from ..pipeline_utils import DiffusionPipeline
32
+ from .pipeline_output import WanPipelineOutput
33
+
34
+
35
+ if is_torch_xla_available():
36
+ import torch_xla.core.xla_model as xm
37
+
38
+ XLA_AVAILABLE = True
39
+ else:
40
+ XLA_AVAILABLE = False
41
+
42
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
43
+
44
+ if is_ftfy_available():
45
+ import ftfy
46
+
47
+ EXAMPLE_DOC_STRING = """
48
+ Examples:
49
+ ```python
50
+ >>> import torch
51
+ >>> import numpy as np
52
+ >>> from diffusers import AutoencoderKLWan, WanImageToVideoPipeline
53
+ >>> from diffusers.utils import export_to_video, load_image
54
+ >>> from transformers import CLIPVisionModel
55
+
56
+ >>> # Available models: Wan-AI/Wan2.1-I2V-14B-480P-Diffusers, Wan-AI/Wan2.1-I2V-14B-720P-Diffusers
57
+ >>> model_id = "Wan-AI/Wan2.1-I2V-14B-480P-Diffusers"
58
+ >>> image_encoder = CLIPVisionModel.from_pretrained(
59
+ ... model_id, subfolder="image_encoder", torch_dtype=torch.float32
60
+ ... )
61
+ >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
62
+ >>> pipe = WanImageToVideoPipeline.from_pretrained(
63
+ ... model_id, vae=vae, image_encoder=image_encoder, torch_dtype=torch.bfloat16
64
+ ... )
65
+ >>> pipe.to("cuda")
66
+
67
+ >>> image = load_image(
68
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
69
+ ... )
70
+ >>> max_area = 480 * 832
71
+ >>> aspect_ratio = image.height / image.width
72
+ >>> mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
73
+ >>> height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
74
+ >>> width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
75
+ >>> image = image.resize((width, height))
76
+ >>> prompt = (
77
+ ... "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in "
78
+ ... "the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
79
+ ... )
80
+ >>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
81
+
82
+ >>> output = pipe(
83
+ ... image=image,
84
+ ... prompt=prompt,
85
+ ... negative_prompt=negative_prompt,
86
+ ... height=height,
87
+ ... width=width,
88
+ ... num_frames=81,
89
+ ... guidance_scale=5.0,
90
+ ... ).frames[0]
91
+ >>> export_to_video(output, "output.mp4", fps=16)
92
+ ```
93
+ """
94
+
95
+
96
+ def basic_clean(text):
97
+ text = ftfy.fix_text(text)
98
+ text = html.unescape(html.unescape(text))
99
+ return text.strip()
100
+
101
+
102
+ def whitespace_clean(text):
103
+ text = re.sub(r"\s+", " ", text)
104
+ text = text.strip()
105
+ return text
106
+
107
+
108
+ def prompt_clean(text):
109
+ text = whitespace_clean(basic_clean(text))
110
+ return text
111
+
112
+
113
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
114
+ def retrieve_latents(
115
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
116
+ ):
117
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
118
+ return encoder_output.latent_dist.sample(generator)
119
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
120
+ return encoder_output.latent_dist.mode()
121
+ elif hasattr(encoder_output, "latents"):
122
+ return encoder_output.latents
123
+ else:
124
+ raise AttributeError("Could not access latents of provided encoder_output")
125
+
126
+
127
+ class WanImageToVideoPipeline(DiffusionPipeline, WanLoraLoaderMixin):
128
+ r"""
129
+ Pipeline for image-to-video generation using Wan.
130
+
131
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
132
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
133
+
134
+ Args:
135
+ tokenizer ([`T5Tokenizer`]):
136
+ Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
137
+ specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
138
+ text_encoder ([`T5EncoderModel`]):
139
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
140
+ the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
141
+ image_encoder ([`CLIPVisionModel`]):
142
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPVisionModel), specifically
143
+ the
144
+ [clip-vit-huge-patch14](https://github.com/mlfoundations/open_clip/blob/main/docs/PRETRAINED.md#vit-h14-xlm-roberta-large)
145
+ variant.
146
+ transformer ([`WanTransformer3DModel`]):
147
+ Conditional Transformer to denoise the input latents.
148
+ scheduler ([`UniPCMultistepScheduler`]):
149
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
150
+ vae ([`AutoencoderKLWan`]):
151
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
152
+ """
153
+
154
+ model_cpu_offload_seq = "text_encoder->image_encoder->transformer->vae"
155
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
156
+
157
+ def __init__(
158
+ self,
159
+ tokenizer: AutoTokenizer,
160
+ text_encoder: UMT5EncoderModel,
161
+ image_encoder: CLIPVisionModel,
162
+ image_processor: CLIPImageProcessor,
163
+ transformer: WanTransformer3DModel,
164
+ vae: AutoencoderKLWan,
165
+ scheduler: FlowMatchEulerDiscreteScheduler,
166
+ ):
167
+ super().__init__()
168
+
169
+ self.register_modules(
170
+ vae=vae,
171
+ text_encoder=text_encoder,
172
+ tokenizer=tokenizer,
173
+ image_encoder=image_encoder,
174
+ transformer=transformer,
175
+ scheduler=scheduler,
176
+ image_processor=image_processor,
177
+ )
178
+
179
+ self.vae_scale_factor_temporal = 2 ** sum(self.vae.temperal_downsample) if getattr(self, "vae", None) else 4
180
+ self.vae_scale_factor_spatial = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8
181
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
182
+ self.image_processor = image_processor
183
+
184
+ def _get_t5_prompt_embeds(
185
+ self,
186
+ prompt: Union[str, List[str]] = None,
187
+ num_videos_per_prompt: int = 1,
188
+ max_sequence_length: int = 512,
189
+ device: Optional[torch.device] = None,
190
+ dtype: Optional[torch.dtype] = None,
191
+ ):
192
+ device = device or self._execution_device
193
+ dtype = dtype or self.text_encoder.dtype
194
+
195
+ prompt = [prompt] if isinstance(prompt, str) else prompt
196
+ prompt = [prompt_clean(u) for u in prompt]
197
+ batch_size = len(prompt)
198
+
199
+ text_inputs = self.tokenizer(
200
+ prompt,
201
+ padding="max_length",
202
+ max_length=max_sequence_length,
203
+ truncation=True,
204
+ add_special_tokens=True,
205
+ return_attention_mask=True,
206
+ return_tensors="pt",
207
+ )
208
+ text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
209
+ seq_lens = mask.gt(0).sum(dim=1).long()
210
+
211
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
212
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
213
+ prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
214
+ prompt_embeds = torch.stack(
215
+ [torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
216
+ )
217
+
218
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
219
+ _, seq_len, _ = prompt_embeds.shape
220
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
221
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
222
+
223
+ return prompt_embeds
224
+
225
+ def encode_image(
226
+ self,
227
+ image: PipelineImageInput,
228
+ device: Optional[torch.device] = None,
229
+ ):
230
+ device = device or self._execution_device
231
+ image = self.image_processor(images=image, return_tensors="pt").to(device)
232
+ image_embeds = self.image_encoder(**image, output_hidden_states=True)
233
+ return image_embeds.hidden_states[-2]
234
+
235
+ # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline.encode_prompt
236
+ def encode_prompt(
237
+ self,
238
+ prompt: Union[str, List[str]],
239
+ negative_prompt: Optional[Union[str, List[str]]] = None,
240
+ do_classifier_free_guidance: bool = True,
241
+ num_videos_per_prompt: int = 1,
242
+ prompt_embeds: Optional[torch.Tensor] = None,
243
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
244
+ max_sequence_length: int = 226,
245
+ device: Optional[torch.device] = None,
246
+ dtype: Optional[torch.dtype] = None,
247
+ ):
248
+ r"""
249
+ Encodes the prompt into text encoder hidden states.
250
+
251
+ Args:
252
+ prompt (`str` or `List[str]`, *optional*):
253
+ prompt to be encoded
254
+ negative_prompt (`str` or `List[str]`, *optional*):
255
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
256
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
257
+ less than `1`).
258
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
259
+ Whether to use classifier free guidance or not.
260
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
261
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
262
+ prompt_embeds (`torch.Tensor`, *optional*):
263
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
264
+ provided, text embeddings will be generated from `prompt` input argument.
265
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
266
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
267
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
268
+ argument.
269
+ device: (`torch.device`, *optional*):
270
+ torch device
271
+ dtype: (`torch.dtype`, *optional*):
272
+ torch dtype
273
+ """
274
+ device = device or self._execution_device
275
+
276
+ prompt = [prompt] if isinstance(prompt, str) else prompt
277
+ if prompt is not None:
278
+ batch_size = len(prompt)
279
+ else:
280
+ batch_size = prompt_embeds.shape[0]
281
+
282
+ if prompt_embeds is None:
283
+ prompt_embeds = self._get_t5_prompt_embeds(
284
+ prompt=prompt,
285
+ num_videos_per_prompt=num_videos_per_prompt,
286
+ max_sequence_length=max_sequence_length,
287
+ device=device,
288
+ dtype=dtype,
289
+ )
290
+
291
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
292
+ negative_prompt = negative_prompt or ""
293
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
294
+
295
+ if prompt is not None and type(prompt) is not type(negative_prompt):
296
+ raise TypeError(
297
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
298
+ f" {type(prompt)}."
299
+ )
300
+ elif batch_size != len(negative_prompt):
301
+ raise ValueError(
302
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
303
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
304
+ " the batch size of `prompt`."
305
+ )
306
+
307
+ negative_prompt_embeds = self._get_t5_prompt_embeds(
308
+ prompt=negative_prompt,
309
+ num_videos_per_prompt=num_videos_per_prompt,
310
+ max_sequence_length=max_sequence_length,
311
+ device=device,
312
+ dtype=dtype,
313
+ )
314
+
315
+ return prompt_embeds, negative_prompt_embeds
316
+
317
+ def check_inputs(
318
+ self,
319
+ prompt,
320
+ negative_prompt,
321
+ image,
322
+ height,
323
+ width,
324
+ prompt_embeds=None,
325
+ negative_prompt_embeds=None,
326
+ image_embeds=None,
327
+ callback_on_step_end_tensor_inputs=None,
328
+ ):
329
+ if image is not None and image_embeds is not None:
330
+ raise ValueError(
331
+ f"Cannot forward both `image`: {image} and `image_embeds`: {image_embeds}. Please make sure to"
332
+ " only forward one of the two."
333
+ )
334
+ if image is None and image_embeds is None:
335
+ raise ValueError(
336
+ "Provide either `image` or `prompt_embeds`. Cannot leave both `image` and `image_embeds` undefined."
337
+ )
338
+ if image is not None and not isinstance(image, torch.Tensor) and not isinstance(image, PIL.Image.Image):
339
+ raise ValueError(f"`image` has to be of type `torch.Tensor` or `PIL.Image.Image` but is {type(image)}")
340
+ if height % 16 != 0 or width % 16 != 0:
341
+ raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
342
+
343
+ if callback_on_step_end_tensor_inputs is not None and not all(
344
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
345
+ ):
346
+ raise ValueError(
347
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
348
+ )
349
+
350
+ if prompt is not None and prompt_embeds is not None:
351
+ raise ValueError(
352
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
353
+ " only forward one of the two."
354
+ )
355
+ elif negative_prompt is not None and negative_prompt_embeds is not None:
356
+ raise ValueError(
357
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
358
+ " only forward one of the two."
359
+ )
360
+ elif prompt is None and prompt_embeds is None:
361
+ raise ValueError(
362
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
363
+ )
364
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
365
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
366
+ elif negative_prompt is not None and (
367
+ not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
368
+ ):
369
+ raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
370
+
371
+ def prepare_latents(
372
+ self,
373
+ image: PipelineImageInput,
374
+ batch_size: int,
375
+ num_channels_latents: int = 16,
376
+ height: int = 480,
377
+ width: int = 832,
378
+ num_frames: int = 81,
379
+ dtype: Optional[torch.dtype] = None,
380
+ device: Optional[torch.device] = None,
381
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
382
+ latents: Optional[torch.Tensor] = None,
383
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
384
+ num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
385
+ latent_height = height // self.vae_scale_factor_spatial
386
+ latent_width = width // self.vae_scale_factor_spatial
387
+
388
+ shape = (batch_size, num_channels_latents, num_latent_frames, latent_height, latent_width)
389
+ if isinstance(generator, list) and len(generator) != batch_size:
390
+ raise ValueError(
391
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
392
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
393
+ )
394
+
395
+ if latents is None:
396
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
397
+ else:
398
+ latents = latents.to(device=device, dtype=dtype)
399
+
400
+ image = image.unsqueeze(2)
401
+ video_condition = torch.cat(
402
+ [image, image.new_zeros(image.shape[0], image.shape[1], num_frames - 1, height, width)], dim=2
403
+ )
404
+ video_condition = video_condition.to(device=device, dtype=dtype)
405
+
406
+ latents_mean = (
407
+ torch.tensor(self.vae.config.latents_mean)
408
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
409
+ .to(latents.device, latents.dtype)
410
+ )
411
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
412
+ latents.device, latents.dtype
413
+ )
414
+
415
+ if isinstance(generator, list):
416
+ latent_condition = [
417
+ retrieve_latents(self.vae.encode(video_condition), sample_mode="argmax") for _ in generator
418
+ ]
419
+ latent_condition = torch.cat(latent_condition)
420
+ else:
421
+ latent_condition = retrieve_latents(self.vae.encode(video_condition), sample_mode="argmax")
422
+ latent_condition = latent_condition.repeat(batch_size, 1, 1, 1, 1)
423
+
424
+ latent_condition = (latent_condition - latents_mean) * latents_std
425
+
426
+ mask_lat_size = torch.ones(batch_size, 1, num_frames, latent_height, latent_width)
427
+ mask_lat_size[:, :, list(range(1, num_frames))] = 0
428
+ first_frame_mask = mask_lat_size[:, :, 0:1]
429
+ first_frame_mask = torch.repeat_interleave(first_frame_mask, dim=2, repeats=self.vae_scale_factor_temporal)
430
+ mask_lat_size = torch.concat([first_frame_mask, mask_lat_size[:, :, 1:, :]], dim=2)
431
+ mask_lat_size = mask_lat_size.view(batch_size, -1, self.vae_scale_factor_temporal, latent_height, latent_width)
432
+ mask_lat_size = mask_lat_size.transpose(1, 2)
433
+ mask_lat_size = mask_lat_size.to(latent_condition.device)
434
+
435
+ return latents, torch.concat([mask_lat_size, latent_condition], dim=1)
436
+
437
+ @property
438
+ def guidance_scale(self):
439
+ return self._guidance_scale
440
+
441
+ @property
442
+ def do_classifier_free_guidance(self):
443
+ return self._guidance_scale > 1
444
+
445
+ @property
446
+ def num_timesteps(self):
447
+ return self._num_timesteps
448
+
449
+ @property
450
+ def current_timestep(self):
451
+ return self._current_timestep
452
+
453
+ @property
454
+ def interrupt(self):
455
+ return self._interrupt
456
+
457
+ @property
458
+ def attention_kwargs(self):
459
+ return self._attention_kwargs
460
+
461
+ @torch.no_grad()
462
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
463
+ def __call__(
464
+ self,
465
+ image: PipelineImageInput,
466
+ prompt: Union[str, List[str]] = None,
467
+ negative_prompt: Union[str, List[str]] = None,
468
+ height: int = 480,
469
+ width: int = 832,
470
+ num_frames: int = 81,
471
+ num_inference_steps: int = 50,
472
+ guidance_scale: float = 5.0,
473
+ num_videos_per_prompt: Optional[int] = 1,
474
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
475
+ latents: Optional[torch.Tensor] = None,
476
+ prompt_embeds: Optional[torch.Tensor] = None,
477
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
478
+ image_embeds: Optional[torch.Tensor] = None,
479
+ output_type: Optional[str] = "np",
480
+ return_dict: bool = True,
481
+ attention_kwargs: Optional[Dict[str, Any]] = None,
482
+ callback_on_step_end: Optional[
483
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
484
+ ] = None,
485
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
486
+ max_sequence_length: int = 512,
487
+ ):
488
+ r"""
489
+ The call function to the pipeline for generation.
490
+
491
+ Args:
492
+ image (`PipelineImageInput`):
493
+ The input image to condition the generation on. Must be an image, a list of images or a `torch.Tensor`.
494
+ prompt (`str` or `List[str]`, *optional*):
495
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
496
+ instead.
497
+ negative_prompt (`str` or `List[str]`, *optional*):
498
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
499
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
500
+ less than `1`).
501
+ height (`int`, defaults to `480`):
502
+ The height of the generated video.
503
+ width (`int`, defaults to `832`):
504
+ The width of the generated video.
505
+ num_frames (`int`, defaults to `81`):
506
+ The number of frames in the generated video.
507
+ num_inference_steps (`int`, defaults to `50`):
508
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
509
+ expense of slower inference.
510
+ guidance_scale (`float`, defaults to `5.0`):
511
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
512
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
513
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
514
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
515
+ usually at the expense of lower image quality.
516
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
517
+ The number of images to generate per prompt.
518
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
519
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
520
+ generation deterministic.
521
+ latents (`torch.Tensor`, *optional*):
522
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
523
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
524
+ tensor is generated by sampling using the supplied random `generator`.
525
+ prompt_embeds (`torch.Tensor`, *optional*):
526
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
527
+ provided, text embeddings are generated from the `prompt` input argument.
528
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
529
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
530
+ provided, text embeddings are generated from the `negative_prompt` input argument.
531
+ image_embeds (`torch.Tensor`, *optional*):
532
+ Pre-generated image embeddings. Can be used to easily tweak image inputs (weighting). If not provided,
533
+ image embeddings are generated from the `image` input argument.
534
+ output_type (`str`, *optional*, defaults to `"pil"`):
535
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
536
+ return_dict (`bool`, *optional*, defaults to `True`):
537
+ Whether or not to return a [`WanPipelineOutput`] instead of a plain tuple.
538
+ attention_kwargs (`dict`, *optional*):
539
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
540
+ `self.processor` in
541
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
542
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
543
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
544
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
545
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
546
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
547
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
548
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
549
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
550
+ `._callback_tensor_inputs` attribute of your pipeline class.
551
+ max_sequence_length (`int`, *optional*, defaults to `512`):
552
+ The maximum sequence length of the prompt.
553
+ shift (`float`, *optional*, defaults to `5.0`):
554
+ The shift of the flow.
555
+ autocast_dtype (`torch.dtype`, *optional*, defaults to `torch.bfloat16`):
556
+ The dtype to use for the torch.amp.autocast.
557
+ Examples:
558
+
559
+ Returns:
560
+ [`~WanPipelineOutput`] or `tuple`:
561
+ If `return_dict` is `True`, [`WanPipelineOutput`] is returned, otherwise a `tuple` is returned where
562
+ the first element is a list with the generated images and the second element is a list of `bool`s
563
+ indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
564
+ """
565
+
566
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
567
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
568
+
569
+ # 1. Check inputs. Raise error if not correct
570
+ self.check_inputs(
571
+ prompt,
572
+ negative_prompt,
573
+ image,
574
+ height,
575
+ width,
576
+ prompt_embeds,
577
+ negative_prompt_embeds,
578
+ image_embeds,
579
+ callback_on_step_end_tensor_inputs,
580
+ )
581
+
582
+ if num_frames % self.vae_scale_factor_temporal != 1:
583
+ logger.warning(
584
+ f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
585
+ )
586
+ num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
587
+ num_frames = max(num_frames, 1)
588
+
589
+ self._guidance_scale = guidance_scale
590
+ self._attention_kwargs = attention_kwargs
591
+ self._current_timestep = None
592
+ self._interrupt = False
593
+
594
+ device = self._execution_device
595
+
596
+ # 2. Define call parameters
597
+ if prompt is not None and isinstance(prompt, str):
598
+ batch_size = 1
599
+ elif prompt is not None and isinstance(prompt, list):
600
+ batch_size = len(prompt)
601
+ else:
602
+ batch_size = prompt_embeds.shape[0]
603
+
604
+ # 3. Encode input prompt
605
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
606
+ prompt=prompt,
607
+ negative_prompt=negative_prompt,
608
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
609
+ num_videos_per_prompt=num_videos_per_prompt,
610
+ prompt_embeds=prompt_embeds,
611
+ negative_prompt_embeds=negative_prompt_embeds,
612
+ max_sequence_length=max_sequence_length,
613
+ device=device,
614
+ )
615
+
616
+ # Encode image embedding
617
+ transformer_dtype = self.transformer.dtype
618
+ prompt_embeds = prompt_embeds.to(transformer_dtype)
619
+ if negative_prompt_embeds is not None:
620
+ negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
621
+
622
+ if image_embeds is None:
623
+ image_embeds = self.encode_image(image, device)
624
+ image_embeds = image_embeds.repeat(batch_size, 1, 1)
625
+ image_embeds = image_embeds.to(transformer_dtype)
626
+
627
+ # 4. Prepare timesteps
628
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
629
+ timesteps = self.scheduler.timesteps
630
+
631
+ # 5. Prepare latent variables
632
+ num_channels_latents = self.vae.config.z_dim
633
+ image = self.video_processor.preprocess(image, height=height, width=width).to(device, dtype=torch.float32)
634
+ latents, condition = self.prepare_latents(
635
+ image,
636
+ batch_size * num_videos_per_prompt,
637
+ num_channels_latents,
638
+ height,
639
+ width,
640
+ num_frames,
641
+ torch.float32,
642
+ device,
643
+ generator,
644
+ latents,
645
+ )
646
+
647
+ # 6. Denoising loop
648
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
649
+ self._num_timesteps = len(timesteps)
650
+
651
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
652
+ for i, t in enumerate(timesteps):
653
+ if self.interrupt:
654
+ continue
655
+
656
+ self._current_timestep = t
657
+ latent_model_input = torch.cat([latents, condition], dim=1).to(transformer_dtype)
658
+ timestep = t.expand(latents.shape[0])
659
+
660
+ noise_pred = self.transformer(
661
+ hidden_states=latent_model_input,
662
+ timestep=timestep,
663
+ encoder_hidden_states=prompt_embeds,
664
+ encoder_hidden_states_image=image_embeds,
665
+ attention_kwargs=attention_kwargs,
666
+ return_dict=False,
667
+ )[0]
668
+
669
+ if self.do_classifier_free_guidance:
670
+ noise_uncond = self.transformer(
671
+ hidden_states=latent_model_input,
672
+ timestep=timestep,
673
+ encoder_hidden_states=negative_prompt_embeds,
674
+ encoder_hidden_states_image=image_embeds,
675
+ attention_kwargs=attention_kwargs,
676
+ return_dict=False,
677
+ )[0]
678
+ noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)
679
+
680
+ # compute the previous noisy sample x_t -> x_t-1
681
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
682
+
683
+ if callback_on_step_end is not None:
684
+ callback_kwargs = {}
685
+ for k in callback_on_step_end_tensor_inputs:
686
+ callback_kwargs[k] = locals()[k]
687
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
688
+
689
+ latents = callback_outputs.pop("latents", latents)
690
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
691
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
692
+
693
+ # call the callback, if provided
694
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
695
+ progress_bar.update()
696
+
697
+ if XLA_AVAILABLE:
698
+ xm.mark_step()
699
+
700
+ self._current_timestep = None
701
+
702
+ if not output_type == "latent":
703
+ latents = latents.to(self.vae.dtype)
704
+ latents_mean = (
705
+ torch.tensor(self.vae.config.latents_mean)
706
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
707
+ .to(latents.device, latents.dtype)
708
+ )
709
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
710
+ latents.device, latents.dtype
711
+ )
712
+ latents = latents / latents_std + latents_mean
713
+ video = self.vae.decode(latents, return_dict=False)[0]
714
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
715
+ else:
716
+ video = latents
717
+
718
+ # Offload all models
719
+ self.maybe_free_model_hooks()
720
+
721
+ if not return_dict:
722
+ return (video,)
723
+
724
+ return WanPipelineOutput(frames=video)