diffusers 0.33.1__py3-none-any.whl → 0.34.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (478) hide show
  1. diffusers/__init__.py +48 -1
  2. diffusers/commands/__init__.py +1 -1
  3. diffusers/commands/diffusers_cli.py +1 -1
  4. diffusers/commands/env.py +1 -1
  5. diffusers/commands/fp16_safetensors.py +1 -1
  6. diffusers/dependency_versions_check.py +1 -1
  7. diffusers/dependency_versions_table.py +1 -1
  8. diffusers/experimental/rl/value_guided_sampling.py +1 -1
  9. diffusers/hooks/faster_cache.py +2 -2
  10. diffusers/hooks/group_offloading.py +128 -29
  11. diffusers/hooks/hooks.py +2 -2
  12. diffusers/hooks/layerwise_casting.py +3 -3
  13. diffusers/hooks/pyramid_attention_broadcast.py +1 -1
  14. diffusers/image_processor.py +7 -2
  15. diffusers/loaders/__init__.py +4 -0
  16. diffusers/loaders/ip_adapter.py +5 -14
  17. diffusers/loaders/lora_base.py +212 -111
  18. diffusers/loaders/lora_conversion_utils.py +275 -34
  19. diffusers/loaders/lora_pipeline.py +1554 -819
  20. diffusers/loaders/peft.py +52 -109
  21. diffusers/loaders/single_file.py +2 -2
  22. diffusers/loaders/single_file_model.py +20 -4
  23. diffusers/loaders/single_file_utils.py +225 -5
  24. diffusers/loaders/textual_inversion.py +3 -2
  25. diffusers/loaders/transformer_flux.py +1 -1
  26. diffusers/loaders/transformer_sd3.py +2 -2
  27. diffusers/loaders/unet.py +2 -16
  28. diffusers/loaders/unet_loader_utils.py +1 -1
  29. diffusers/loaders/utils.py +1 -1
  30. diffusers/models/__init__.py +15 -1
  31. diffusers/models/activations.py +5 -5
  32. diffusers/models/adapter.py +2 -3
  33. diffusers/models/attention.py +4 -4
  34. diffusers/models/attention_flax.py +10 -10
  35. diffusers/models/attention_processor.py +14 -10
  36. diffusers/models/auto_model.py +47 -10
  37. diffusers/models/autoencoders/__init__.py +1 -0
  38. diffusers/models/autoencoders/autoencoder_asym_kl.py +4 -4
  39. diffusers/models/autoencoders/autoencoder_dc.py +3 -3
  40. diffusers/models/autoencoders/autoencoder_kl.py +4 -4
  41. diffusers/models/autoencoders/autoencoder_kl_allegro.py +4 -4
  42. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +6 -6
  43. diffusers/models/autoencoders/autoencoder_kl_cosmos.py +1108 -0
  44. diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py +2 -2
  45. diffusers/models/autoencoders/autoencoder_kl_ltx.py +3 -3
  46. diffusers/models/autoencoders/autoencoder_kl_magvit.py +4 -4
  47. diffusers/models/autoencoders/autoencoder_kl_mochi.py +3 -3
  48. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +4 -4
  49. diffusers/models/autoencoders/autoencoder_kl_wan.py +256 -22
  50. diffusers/models/autoencoders/autoencoder_oobleck.py +1 -1
  51. diffusers/models/autoencoders/autoencoder_tiny.py +3 -3
  52. diffusers/models/autoencoders/consistency_decoder_vae.py +1 -1
  53. diffusers/models/autoencoders/vae.py +13 -2
  54. diffusers/models/autoencoders/vq_model.py +2 -2
  55. diffusers/models/cache_utils.py +1 -1
  56. diffusers/models/controlnet.py +1 -1
  57. diffusers/models/controlnet_flux.py +1 -1
  58. diffusers/models/controlnet_sd3.py +1 -1
  59. diffusers/models/controlnet_sparsectrl.py +1 -1
  60. diffusers/models/controlnets/__init__.py +1 -0
  61. diffusers/models/controlnets/controlnet.py +3 -3
  62. diffusers/models/controlnets/controlnet_flax.py +1 -1
  63. diffusers/models/controlnets/controlnet_flux.py +16 -15
  64. diffusers/models/controlnets/controlnet_hunyuan.py +2 -2
  65. diffusers/models/controlnets/controlnet_sana.py +290 -0
  66. diffusers/models/controlnets/controlnet_sd3.py +1 -1
  67. diffusers/models/controlnets/controlnet_sparsectrl.py +2 -2
  68. diffusers/models/controlnets/controlnet_union.py +1 -1
  69. diffusers/models/controlnets/controlnet_xs.py +7 -7
  70. diffusers/models/controlnets/multicontrolnet.py +4 -5
  71. diffusers/models/controlnets/multicontrolnet_union.py +5 -6
  72. diffusers/models/downsampling.py +2 -2
  73. diffusers/models/embeddings.py +10 -12
  74. diffusers/models/embeddings_flax.py +2 -2
  75. diffusers/models/lora.py +3 -3
  76. diffusers/models/modeling_utils.py +44 -14
  77. diffusers/models/normalization.py +4 -4
  78. diffusers/models/resnet.py +2 -2
  79. diffusers/models/resnet_flax.py +1 -1
  80. diffusers/models/transformers/__init__.py +5 -0
  81. diffusers/models/transformers/auraflow_transformer_2d.py +70 -24
  82. diffusers/models/transformers/cogvideox_transformer_3d.py +1 -1
  83. diffusers/models/transformers/consisid_transformer_3d.py +1 -1
  84. diffusers/models/transformers/dit_transformer_2d.py +2 -2
  85. diffusers/models/transformers/dual_transformer_2d.py +1 -1
  86. diffusers/models/transformers/hunyuan_transformer_2d.py +2 -2
  87. diffusers/models/transformers/latte_transformer_3d.py +4 -5
  88. diffusers/models/transformers/lumina_nextdit2d.py +2 -2
  89. diffusers/models/transformers/pixart_transformer_2d.py +3 -3
  90. diffusers/models/transformers/prior_transformer.py +1 -1
  91. diffusers/models/transformers/sana_transformer.py +8 -3
  92. diffusers/models/transformers/stable_audio_transformer.py +5 -9
  93. diffusers/models/transformers/t5_film_transformer.py +3 -3
  94. diffusers/models/transformers/transformer_2d.py +1 -1
  95. diffusers/models/transformers/transformer_allegro.py +1 -1
  96. diffusers/models/transformers/transformer_chroma.py +742 -0
  97. diffusers/models/transformers/transformer_cogview3plus.py +5 -10
  98. diffusers/models/transformers/transformer_cogview4.py +317 -25
  99. diffusers/models/transformers/transformer_cosmos.py +579 -0
  100. diffusers/models/transformers/transformer_flux.py +9 -11
  101. diffusers/models/transformers/transformer_hidream_image.py +942 -0
  102. diffusers/models/transformers/transformer_hunyuan_video.py +6 -8
  103. diffusers/models/transformers/transformer_hunyuan_video_framepack.py +416 -0
  104. diffusers/models/transformers/transformer_ltx.py +2 -2
  105. diffusers/models/transformers/transformer_lumina2.py +1 -1
  106. diffusers/models/transformers/transformer_mochi.py +1 -1
  107. diffusers/models/transformers/transformer_omnigen.py +2 -2
  108. diffusers/models/transformers/transformer_sd3.py +7 -7
  109. diffusers/models/transformers/transformer_temporal.py +1 -1
  110. diffusers/models/transformers/transformer_wan.py +24 -8
  111. diffusers/models/transformers/transformer_wan_vace.py +393 -0
  112. diffusers/models/unets/unet_1d.py +1 -1
  113. diffusers/models/unets/unet_1d_blocks.py +1 -1
  114. diffusers/models/unets/unet_2d.py +1 -1
  115. diffusers/models/unets/unet_2d_blocks.py +1 -1
  116. diffusers/models/unets/unet_2d_blocks_flax.py +8 -7
  117. diffusers/models/unets/unet_2d_condition.py +2 -2
  118. diffusers/models/unets/unet_2d_condition_flax.py +2 -2
  119. diffusers/models/unets/unet_3d_blocks.py +1 -1
  120. diffusers/models/unets/unet_3d_condition.py +3 -3
  121. diffusers/models/unets/unet_i2vgen_xl.py +3 -3
  122. diffusers/models/unets/unet_kandinsky3.py +1 -1
  123. diffusers/models/unets/unet_motion_model.py +2 -2
  124. diffusers/models/unets/unet_stable_cascade.py +1 -1
  125. diffusers/models/upsampling.py +2 -2
  126. diffusers/models/vae_flax.py +2 -2
  127. diffusers/models/vq_model.py +1 -1
  128. diffusers/pipelines/__init__.py +37 -6
  129. diffusers/pipelines/allegro/pipeline_allegro.py +11 -11
  130. diffusers/pipelines/amused/pipeline_amused.py +7 -6
  131. diffusers/pipelines/amused/pipeline_amused_img2img.py +6 -5
  132. diffusers/pipelines/amused/pipeline_amused_inpaint.py +6 -5
  133. diffusers/pipelines/animatediff/pipeline_animatediff.py +6 -6
  134. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +6 -6
  135. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +16 -15
  136. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +6 -6
  137. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +5 -5
  138. diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +5 -5
  139. diffusers/pipelines/audioldm/pipeline_audioldm.py +8 -7
  140. diffusers/pipelines/audioldm2/modeling_audioldm2.py +1 -1
  141. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +23 -13
  142. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +48 -11
  143. diffusers/pipelines/auto_pipeline.py +6 -7
  144. diffusers/pipelines/blip_diffusion/modeling_blip2.py +1 -1
  145. diffusers/pipelines/blip_diffusion/modeling_ctx_clip.py +2 -2
  146. diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +11 -10
  147. diffusers/pipelines/chroma/__init__.py +49 -0
  148. diffusers/pipelines/chroma/pipeline_chroma.py +949 -0
  149. diffusers/pipelines/chroma/pipeline_chroma_img2img.py +1034 -0
  150. diffusers/pipelines/chroma/pipeline_output.py +21 -0
  151. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +8 -8
  152. diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +8 -8
  153. diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +8 -8
  154. diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +8 -8
  155. diffusers/pipelines/cogview3/pipeline_cogview3plus.py +9 -9
  156. diffusers/pipelines/cogview4/pipeline_cogview4.py +7 -7
  157. diffusers/pipelines/cogview4/pipeline_cogview4_control.py +7 -7
  158. diffusers/pipelines/consisid/consisid_utils.py +2 -2
  159. diffusers/pipelines/consisid/pipeline_consisid.py +8 -8
  160. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -1
  161. diffusers/pipelines/controlnet/pipeline_controlnet.py +7 -7
  162. diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +8 -8
  163. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +7 -7
  164. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +7 -7
  165. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +14 -14
  166. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +10 -6
  167. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +13 -13
  168. diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +14 -14
  169. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +5 -5
  170. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +13 -13
  171. diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +1 -1
  172. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +8 -8
  173. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +7 -7
  174. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +7 -7
  175. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +12 -10
  176. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +9 -7
  177. diffusers/pipelines/cosmos/__init__.py +54 -0
  178. diffusers/pipelines/cosmos/pipeline_cosmos2_text2image.py +673 -0
  179. diffusers/pipelines/cosmos/pipeline_cosmos2_video2world.py +792 -0
  180. diffusers/pipelines/cosmos/pipeline_cosmos_text2world.py +664 -0
  181. diffusers/pipelines/cosmos/pipeline_cosmos_video2world.py +826 -0
  182. diffusers/pipelines/cosmos/pipeline_output.py +40 -0
  183. diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +5 -4
  184. diffusers/pipelines/ddim/pipeline_ddim.py +4 -4
  185. diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -1
  186. diffusers/pipelines/deepfloyd_if/pipeline_if.py +10 -10
  187. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +10 -10
  188. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +10 -10
  189. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +10 -10
  190. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +10 -10
  191. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +10 -10
  192. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +8 -8
  193. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +5 -5
  194. diffusers/pipelines/deprecated/audio_diffusion/mel.py +1 -1
  195. diffusers/pipelines/deprecated/audio_diffusion/pipeline_audio_diffusion.py +3 -3
  196. diffusers/pipelines/deprecated/latent_diffusion_uncond/pipeline_latent_diffusion_uncond.py +1 -1
  197. diffusers/pipelines/deprecated/pndm/pipeline_pndm.py +2 -2
  198. diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +4 -3
  199. diffusers/pipelines/deprecated/score_sde_ve/pipeline_score_sde_ve.py +1 -1
  200. diffusers/pipelines/deprecated/spectrogram_diffusion/continuous_encoder.py +1 -1
  201. diffusers/pipelines/deprecated/spectrogram_diffusion/midi_utils.py +1 -1
  202. diffusers/pipelines/deprecated/spectrogram_diffusion/notes_encoder.py +1 -1
  203. diffusers/pipelines/deprecated/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +1 -1
  204. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +7 -7
  205. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_onnx_stable_diffusion_inpaint_legacy.py +9 -9
  206. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +10 -10
  207. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +10 -8
  208. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +5 -5
  209. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +18 -18
  210. diffusers/pipelines/deprecated/stochastic_karras_ve/pipeline_stochastic_karras_ve.py +1 -1
  211. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +2 -2
  212. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py +6 -6
  213. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +5 -5
  214. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +5 -5
  215. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +5 -5
  216. diffusers/pipelines/deprecated/vq_diffusion/pipeline_vq_diffusion.py +1 -1
  217. diffusers/pipelines/dit/pipeline_dit.py +1 -1
  218. diffusers/pipelines/easyanimate/pipeline_easyanimate.py +4 -4
  219. diffusers/pipelines/easyanimate/pipeline_easyanimate_control.py +4 -4
  220. diffusers/pipelines/easyanimate/pipeline_easyanimate_inpaint.py +7 -6
  221. diffusers/pipelines/flux/modeling_flux.py +1 -1
  222. diffusers/pipelines/flux/pipeline_flux.py +10 -17
  223. diffusers/pipelines/flux/pipeline_flux_control.py +6 -6
  224. diffusers/pipelines/flux/pipeline_flux_control_img2img.py +6 -6
  225. diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +6 -6
  226. diffusers/pipelines/flux/pipeline_flux_controlnet.py +6 -6
  227. diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +30 -22
  228. diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +2 -1
  229. diffusers/pipelines/flux/pipeline_flux_fill.py +6 -6
  230. diffusers/pipelines/flux/pipeline_flux_img2img.py +39 -6
  231. diffusers/pipelines/flux/pipeline_flux_inpaint.py +11 -6
  232. diffusers/pipelines/flux/pipeline_flux_prior_redux.py +1 -1
  233. diffusers/pipelines/free_init_utils.py +2 -2
  234. diffusers/pipelines/free_noise_utils.py +3 -3
  235. diffusers/pipelines/hidream_image/__init__.py +47 -0
  236. diffusers/pipelines/hidream_image/pipeline_hidream_image.py +1026 -0
  237. diffusers/pipelines/hidream_image/pipeline_output.py +35 -0
  238. diffusers/pipelines/hunyuan_video/__init__.py +2 -0
  239. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_skyreels_image2video.py +8 -8
  240. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +8 -8
  241. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video_framepack.py +1114 -0
  242. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video_image2video.py +71 -15
  243. diffusers/pipelines/hunyuan_video/pipeline_output.py +19 -0
  244. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +8 -8
  245. diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +10 -8
  246. diffusers/pipelines/kandinsky/pipeline_kandinsky.py +6 -6
  247. diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +34 -34
  248. diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +19 -26
  249. diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +7 -7
  250. diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +11 -11
  251. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +6 -6
  252. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +35 -35
  253. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +6 -6
  254. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +17 -39
  255. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +17 -45
  256. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +7 -7
  257. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +10 -10
  258. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +10 -10
  259. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +7 -7
  260. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +17 -38
  261. diffusers/pipelines/kolors/pipeline_kolors.py +10 -10
  262. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +12 -12
  263. diffusers/pipelines/kolors/text_encoder.py +3 -3
  264. diffusers/pipelines/kolors/tokenizer.py +1 -1
  265. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +2 -2
  266. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +2 -2
  267. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -1
  268. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion_superresolution.py +3 -3
  269. diffusers/pipelines/latte/pipeline_latte.py +12 -12
  270. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +13 -13
  271. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +17 -16
  272. diffusers/pipelines/ltx/__init__.py +4 -0
  273. diffusers/pipelines/ltx/modeling_latent_upsampler.py +188 -0
  274. diffusers/pipelines/ltx/pipeline_ltx.py +51 -6
  275. diffusers/pipelines/ltx/pipeline_ltx_condition.py +107 -29
  276. diffusers/pipelines/ltx/pipeline_ltx_image2video.py +50 -6
  277. diffusers/pipelines/ltx/pipeline_ltx_latent_upsample.py +277 -0
  278. diffusers/pipelines/lumina/pipeline_lumina.py +13 -13
  279. diffusers/pipelines/lumina2/pipeline_lumina2.py +10 -10
  280. diffusers/pipelines/marigold/marigold_image_processing.py +2 -2
  281. diffusers/pipelines/mochi/pipeline_mochi.py +6 -6
  282. diffusers/pipelines/musicldm/pipeline_musicldm.py +16 -13
  283. diffusers/pipelines/omnigen/pipeline_omnigen.py +13 -11
  284. diffusers/pipelines/omnigen/processor_omnigen.py +8 -3
  285. diffusers/pipelines/onnx_utils.py +15 -2
  286. diffusers/pipelines/pag/pag_utils.py +2 -2
  287. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +12 -8
  288. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +7 -7
  289. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +10 -6
  290. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +14 -14
  291. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +8 -8
  292. diffusers/pipelines/pag/pipeline_pag_kolors.py +10 -10
  293. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +11 -11
  294. diffusers/pipelines/pag/pipeline_pag_sana.py +18 -12
  295. diffusers/pipelines/pag/pipeline_pag_sd.py +8 -8
  296. diffusers/pipelines/pag/pipeline_pag_sd_3.py +7 -7
  297. diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +7 -7
  298. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +6 -6
  299. diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +5 -5
  300. diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +8 -8
  301. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +16 -15
  302. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +18 -17
  303. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +12 -12
  304. diffusers/pipelines/paint_by_example/image_encoder.py +1 -1
  305. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +8 -7
  306. diffusers/pipelines/pia/pipeline_pia.py +8 -6
  307. diffusers/pipelines/pipeline_flax_utils.py +3 -4
  308. diffusers/pipelines/pipeline_loading_utils.py +89 -13
  309. diffusers/pipelines/pipeline_utils.py +105 -33
  310. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +11 -11
  311. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +11 -11
  312. diffusers/pipelines/sana/__init__.py +4 -0
  313. diffusers/pipelines/sana/pipeline_sana.py +23 -21
  314. diffusers/pipelines/sana/pipeline_sana_controlnet.py +1106 -0
  315. diffusers/pipelines/sana/pipeline_sana_sprint.py +23 -19
  316. diffusers/pipelines/sana/pipeline_sana_sprint_img2img.py +981 -0
  317. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +7 -6
  318. diffusers/pipelines/shap_e/camera.py +1 -1
  319. diffusers/pipelines/shap_e/pipeline_shap_e.py +1 -1
  320. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +1 -1
  321. diffusers/pipelines/shap_e/renderer.py +3 -3
  322. diffusers/pipelines/stable_audio/modeling_stable_audio.py +1 -1
  323. diffusers/pipelines/stable_audio/pipeline_stable_audio.py +5 -5
  324. diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +8 -8
  325. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +13 -13
  326. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +9 -9
  327. diffusers/pipelines/stable_diffusion/__init__.py +0 -7
  328. diffusers/pipelines/stable_diffusion/clip_image_project_model.py +1 -1
  329. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +11 -4
  330. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
  331. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_img2img.py +1 -1
  332. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_inpaint.py +1 -1
  333. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +10 -10
  334. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +10 -10
  335. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +10 -10
  336. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +9 -9
  337. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +8 -8
  338. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +5 -5
  339. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +5 -5
  340. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +5 -5
  341. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +5 -5
  342. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +5 -5
  343. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +4 -4
  344. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +5 -5
  345. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +7 -7
  346. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +5 -5
  347. diffusers/pipelines/stable_diffusion/safety_checker.py +1 -1
  348. diffusers/pipelines/stable_diffusion/safety_checker_flax.py +1 -1
  349. diffusers/pipelines/stable_diffusion/stable_unclip_image_normalizer.py +1 -1
  350. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +7 -7
  351. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +7 -7
  352. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +7 -7
  353. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +12 -8
  354. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +15 -9
  355. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +11 -9
  356. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +11 -9
  357. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +18 -12
  358. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +11 -8
  359. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +11 -8
  360. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +15 -12
  361. diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +8 -6
  362. diffusers/pipelines/stable_diffusion_safe/safety_checker.py +1 -1
  363. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +15 -11
  364. diffusers/pipelines/stable_diffusion_xl/pipeline_flax_stable_diffusion_xl.py +1 -1
  365. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +16 -15
  366. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +18 -17
  367. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +12 -12
  368. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +16 -15
  369. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +3 -3
  370. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +12 -12
  371. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +18 -17
  372. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +12 -7
  373. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +12 -7
  374. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +15 -13
  375. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +24 -21
  376. diffusers/pipelines/unclip/pipeline_unclip.py +4 -3
  377. diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +4 -3
  378. diffusers/pipelines/unclip/text_proj.py +2 -2
  379. diffusers/pipelines/unidiffuser/modeling_text_decoder.py +2 -2
  380. diffusers/pipelines/unidiffuser/modeling_uvit.py +1 -1
  381. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +8 -7
  382. diffusers/pipelines/visualcloze/__init__.py +52 -0
  383. diffusers/pipelines/visualcloze/pipeline_visualcloze_combined.py +444 -0
  384. diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py +952 -0
  385. diffusers/pipelines/visualcloze/visualcloze_utils.py +251 -0
  386. diffusers/pipelines/wan/__init__.py +2 -0
  387. diffusers/pipelines/wan/pipeline_wan.py +13 -10
  388. diffusers/pipelines/wan/pipeline_wan_i2v.py +38 -18
  389. diffusers/pipelines/wan/pipeline_wan_vace.py +976 -0
  390. diffusers/pipelines/wan/pipeline_wan_video2video.py +14 -16
  391. diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +1 -1
  392. diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py +1 -1
  393. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +1 -1
  394. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +8 -8
  395. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +16 -15
  396. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +6 -6
  397. diffusers/quantizers/__init__.py +179 -1
  398. diffusers/quantizers/base.py +6 -1
  399. diffusers/quantizers/bitsandbytes/bnb_quantizer.py +4 -0
  400. diffusers/quantizers/bitsandbytes/utils.py +10 -7
  401. diffusers/quantizers/gguf/gguf_quantizer.py +13 -4
  402. diffusers/quantizers/gguf/utils.py +16 -13
  403. diffusers/quantizers/quantization_config.py +18 -16
  404. diffusers/quantizers/quanto/quanto_quantizer.py +4 -0
  405. diffusers/quantizers/torchao/torchao_quantizer.py +5 -1
  406. diffusers/schedulers/__init__.py +3 -1
  407. diffusers/schedulers/deprecated/scheduling_karras_ve.py +4 -3
  408. diffusers/schedulers/deprecated/scheduling_sde_vp.py +1 -1
  409. diffusers/schedulers/scheduling_consistency_models.py +1 -1
  410. diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +10 -5
  411. diffusers/schedulers/scheduling_ddim.py +8 -8
  412. diffusers/schedulers/scheduling_ddim_cogvideox.py +5 -5
  413. diffusers/schedulers/scheduling_ddim_flax.py +6 -6
  414. diffusers/schedulers/scheduling_ddim_inverse.py +6 -6
  415. diffusers/schedulers/scheduling_ddim_parallel.py +22 -22
  416. diffusers/schedulers/scheduling_ddpm.py +9 -9
  417. diffusers/schedulers/scheduling_ddpm_flax.py +7 -7
  418. diffusers/schedulers/scheduling_ddpm_parallel.py +18 -18
  419. diffusers/schedulers/scheduling_ddpm_wuerstchen.py +2 -2
  420. diffusers/schedulers/scheduling_deis_multistep.py +8 -8
  421. diffusers/schedulers/scheduling_dpm_cogvideox.py +5 -5
  422. diffusers/schedulers/scheduling_dpmsolver_multistep.py +12 -12
  423. diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py +22 -20
  424. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +11 -11
  425. diffusers/schedulers/scheduling_dpmsolver_sde.py +2 -2
  426. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +13 -13
  427. diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +13 -8
  428. diffusers/schedulers/scheduling_edm_euler.py +20 -11
  429. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +3 -3
  430. diffusers/schedulers/scheduling_euler_discrete.py +3 -3
  431. diffusers/schedulers/scheduling_euler_discrete_flax.py +3 -3
  432. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +20 -5
  433. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +1 -1
  434. diffusers/schedulers/scheduling_flow_match_lcm.py +561 -0
  435. diffusers/schedulers/scheduling_heun_discrete.py +2 -2
  436. diffusers/schedulers/scheduling_ipndm.py +2 -2
  437. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +2 -2
  438. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +2 -2
  439. diffusers/schedulers/scheduling_karras_ve_flax.py +5 -5
  440. diffusers/schedulers/scheduling_lcm.py +3 -3
  441. diffusers/schedulers/scheduling_lms_discrete.py +2 -2
  442. diffusers/schedulers/scheduling_lms_discrete_flax.py +1 -1
  443. diffusers/schedulers/scheduling_pndm.py +4 -4
  444. diffusers/schedulers/scheduling_pndm_flax.py +4 -4
  445. diffusers/schedulers/scheduling_repaint.py +9 -9
  446. diffusers/schedulers/scheduling_sasolver.py +15 -15
  447. diffusers/schedulers/scheduling_scm.py +1 -1
  448. diffusers/schedulers/scheduling_sde_ve.py +1 -1
  449. diffusers/schedulers/scheduling_sde_ve_flax.py +2 -2
  450. diffusers/schedulers/scheduling_tcd.py +3 -3
  451. diffusers/schedulers/scheduling_unclip.py +5 -5
  452. diffusers/schedulers/scheduling_unipc_multistep.py +11 -11
  453. diffusers/schedulers/scheduling_utils.py +1 -1
  454. diffusers/schedulers/scheduling_utils_flax.py +1 -1
  455. diffusers/schedulers/scheduling_vq_diffusion.py +1 -1
  456. diffusers/training_utils.py +13 -5
  457. diffusers/utils/__init__.py +5 -0
  458. diffusers/utils/accelerate_utils.py +1 -1
  459. diffusers/utils/doc_utils.py +1 -1
  460. diffusers/utils/dummy_pt_objects.py +120 -0
  461. diffusers/utils/dummy_torch_and_transformers_objects.py +225 -0
  462. diffusers/utils/dynamic_modules_utils.py +21 -3
  463. diffusers/utils/export_utils.py +1 -1
  464. diffusers/utils/import_utils.py +81 -18
  465. diffusers/utils/logging.py +1 -1
  466. diffusers/utils/outputs.py +2 -1
  467. diffusers/utils/peft_utils.py +91 -8
  468. diffusers/utils/state_dict_utils.py +20 -3
  469. diffusers/utils/testing_utils.py +59 -7
  470. diffusers/utils/torch_utils.py +25 -5
  471. diffusers/video_processor.py +2 -2
  472. {diffusers-0.33.1.dist-info → diffusers-0.34.0.dist-info}/METADATA +70 -55
  473. diffusers-0.34.0.dist-info/RECORD +639 -0
  474. {diffusers-0.33.1.dist-info → diffusers-0.34.0.dist-info}/WHEEL +1 -1
  475. diffusers-0.33.1.dist-info/RECORD +0 -608
  476. {diffusers-0.33.1.dist-info → diffusers-0.34.0.dist-info}/LICENSE +0 -0
  477. {diffusers-0.33.1.dist-info → diffusers-0.34.0.dist-info}/entry_points.txt +0 -0
  478. {diffusers-0.33.1.dist-info → diffusers-0.34.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,976 @@
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, Union
17
+
18
+ import PIL.Image
19
+ import regex as re
20
+ import torch
21
+ from transformers import AutoTokenizer, UMT5EncoderModel
22
+
23
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
24
+ from ...image_processor import PipelineImageInput
25
+ from ...loaders import WanLoraLoaderMixin
26
+ from ...models import AutoencoderKLWan, WanVACETransformer3DModel
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
+
48
+ EXAMPLE_DOC_STRING = """
49
+ Examples:
50
+ ```python
51
+ >>> import torch
52
+ >>> import PIL.Image
53
+ >>> from diffusers import AutoencoderKLWan, WanVACEPipeline
54
+ >>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
55
+ >>> from diffusers.utils import export_to_video, load_image
56
+ def prepare_video_and_mask(first_img: PIL.Image.Image, last_img: PIL.Image.Image, height: int, width: int, num_frames: int):
57
+ first_img = first_img.resize((width, height))
58
+ last_img = last_img.resize((width, height))
59
+ frames = []
60
+ frames.append(first_img)
61
+ # Ideally, this should be 127.5 to match original code, but they perform computation on numpy arrays
62
+ # whereas we are passing PIL images. If you choose to pass numpy arrays, you can set it to 127.5 to
63
+ # match the original code.
64
+ frames.extend([PIL.Image.new("RGB", (width, height), (128, 128, 128))] * (num_frames - 2))
65
+ frames.append(last_img)
66
+ mask_black = PIL.Image.new("L", (width, height), 0)
67
+ mask_white = PIL.Image.new("L", (width, height), 255)
68
+ mask = [mask_black, *[mask_white] * (num_frames - 2), mask_black]
69
+ return frames, mask
70
+
71
+ >>> # Available checkpoints: Wan-AI/Wan2.1-VACE-1.3B-diffusers, Wan-AI/Wan2.1-VACE-14B-diffusers
72
+ >>> model_id = "Wan-AI/Wan2.1-VACE-1.3B-diffusers"
73
+ >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
74
+ >>> pipe = WanVACEPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
75
+ >>> flow_shift = 3.0 # 5.0 for 720P, 3.0 for 480P
76
+ >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
77
+ >>> pipe.to("cuda")
78
+
79
+ >>> prompt = "CG animation style, a small blue bird takes off from the ground, flapping its wings. The bird's feathers are delicate, with a unique pattern on its chest. The background shows a blue sky with white clouds under bright sunshine. The camera follows the bird upward, capturing its flight and the vastness of the sky from a close-up, low-angle perspective."
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
+ >>> first_frame = load_image(
82
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_first_frame.png"
83
+ ... )
84
+ >>> last_frame = load_image(
85
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_last_frame.png>>> "
86
+ ... )
87
+
88
+ >>> height = 512
89
+ >>> width = 512
90
+ >>> num_frames = 81
91
+ >>> video, mask = prepare_video_and_mask(first_frame, last_frame, height, width, num_frames)
92
+
93
+ >>> output = pipe(
94
+ ... video=video,
95
+ ... mask=mask,
96
+ ... prompt=prompt,
97
+ ... negative_prompt=negative_prompt,
98
+ ... height=height,
99
+ ... width=width,
100
+ ... num_frames=num_frames,
101
+ ... num_inference_steps=30,
102
+ ... guidance_scale=5.0,
103
+ ... generator=torch.Generator().manual_seed(42),
104
+ ... ).frames[0]
105
+ >>> export_to_video(output, "output.mp4", fps=16)
106
+ ```
107
+ """
108
+
109
+
110
+ def basic_clean(text):
111
+ text = ftfy.fix_text(text)
112
+ text = html.unescape(html.unescape(text))
113
+ return text.strip()
114
+
115
+
116
+ def whitespace_clean(text):
117
+ text = re.sub(r"\s+", " ", text)
118
+ text = text.strip()
119
+ return text
120
+
121
+
122
+ def prompt_clean(text):
123
+ text = whitespace_clean(basic_clean(text))
124
+ return text
125
+
126
+
127
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
128
+ def retrieve_latents(
129
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
130
+ ):
131
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
132
+ return encoder_output.latent_dist.sample(generator)
133
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
134
+ return encoder_output.latent_dist.mode()
135
+ elif hasattr(encoder_output, "latents"):
136
+ return encoder_output.latents
137
+ else:
138
+ raise AttributeError("Could not access latents of provided encoder_output")
139
+
140
+
141
+ class WanVACEPipeline(DiffusionPipeline, WanLoraLoaderMixin):
142
+ r"""
143
+ Pipeline for controllable generation using Wan.
144
+
145
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
146
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
147
+
148
+ Args:
149
+ tokenizer ([`T5Tokenizer`]):
150
+ Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
151
+ specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
152
+ text_encoder ([`T5EncoderModel`]):
153
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
154
+ the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
155
+ transformer ([`WanTransformer3DModel`]):
156
+ Conditional Transformer to denoise the input latents.
157
+ scheduler ([`UniPCMultistepScheduler`]):
158
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
159
+ vae ([`AutoencoderKLWan`]):
160
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
161
+ """
162
+
163
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
164
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
165
+
166
+ def __init__(
167
+ self,
168
+ tokenizer: AutoTokenizer,
169
+ text_encoder: UMT5EncoderModel,
170
+ transformer: WanVACETransformer3DModel,
171
+ vae: AutoencoderKLWan,
172
+ scheduler: FlowMatchEulerDiscreteScheduler,
173
+ ):
174
+ super().__init__()
175
+
176
+ self.register_modules(
177
+ vae=vae,
178
+ text_encoder=text_encoder,
179
+ tokenizer=tokenizer,
180
+ transformer=transformer,
181
+ scheduler=scheduler,
182
+ )
183
+
184
+ self.vae_scale_factor_temporal = 2 ** sum(self.vae.temperal_downsample) if getattr(self, "vae", None) else 4
185
+ self.vae_scale_factor_spatial = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8
186
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
187
+
188
+ # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline._get_t5_prompt_embeds
189
+ def _get_t5_prompt_embeds(
190
+ self,
191
+ prompt: Union[str, List[str]] = None,
192
+ num_videos_per_prompt: int = 1,
193
+ max_sequence_length: int = 226,
194
+ device: Optional[torch.device] = None,
195
+ dtype: Optional[torch.dtype] = None,
196
+ ):
197
+ device = device or self._execution_device
198
+ dtype = dtype or self.text_encoder.dtype
199
+
200
+ prompt = [prompt] if isinstance(prompt, str) else prompt
201
+ prompt = [prompt_clean(u) for u in prompt]
202
+ batch_size = len(prompt)
203
+
204
+ text_inputs = self.tokenizer(
205
+ prompt,
206
+ padding="max_length",
207
+ max_length=max_sequence_length,
208
+ truncation=True,
209
+ add_special_tokens=True,
210
+ return_attention_mask=True,
211
+ return_tensors="pt",
212
+ )
213
+ text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
214
+ seq_lens = mask.gt(0).sum(dim=1).long()
215
+
216
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
217
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
218
+ prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
219
+ prompt_embeds = torch.stack(
220
+ [torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
221
+ )
222
+
223
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
224
+ _, seq_len, _ = prompt_embeds.shape
225
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
226
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
227
+
228
+ return prompt_embeds
229
+
230
+ # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline.encode_prompt
231
+ def encode_prompt(
232
+ self,
233
+ prompt: Union[str, List[str]],
234
+ negative_prompt: Optional[Union[str, List[str]]] = None,
235
+ do_classifier_free_guidance: bool = True,
236
+ num_videos_per_prompt: int = 1,
237
+ prompt_embeds: Optional[torch.Tensor] = None,
238
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
239
+ max_sequence_length: int = 226,
240
+ device: Optional[torch.device] = None,
241
+ dtype: Optional[torch.dtype] = None,
242
+ ):
243
+ r"""
244
+ Encodes the prompt into text encoder hidden states.
245
+
246
+ Args:
247
+ prompt (`str` or `List[str]`, *optional*):
248
+ prompt to be encoded
249
+ negative_prompt (`str` or `List[str]`, *optional*):
250
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
251
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
252
+ less than `1`).
253
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
254
+ Whether to use classifier free guidance or not.
255
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
256
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
257
+ prompt_embeds (`torch.Tensor`, *optional*):
258
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
259
+ provided, text embeddings will be generated from `prompt` input argument.
260
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
261
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
262
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
263
+ argument.
264
+ device: (`torch.device`, *optional*):
265
+ torch device
266
+ dtype: (`torch.dtype`, *optional*):
267
+ torch dtype
268
+ """
269
+ device = device or self._execution_device
270
+
271
+ prompt = [prompt] if isinstance(prompt, str) else prompt
272
+ if prompt is not None:
273
+ batch_size = len(prompt)
274
+ else:
275
+ batch_size = prompt_embeds.shape[0]
276
+
277
+ if prompt_embeds is None:
278
+ prompt_embeds = self._get_t5_prompt_embeds(
279
+ prompt=prompt,
280
+ num_videos_per_prompt=num_videos_per_prompt,
281
+ max_sequence_length=max_sequence_length,
282
+ device=device,
283
+ dtype=dtype,
284
+ )
285
+
286
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
287
+ negative_prompt = negative_prompt or ""
288
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
289
+
290
+ if prompt is not None and type(prompt) is not type(negative_prompt):
291
+ raise TypeError(
292
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
293
+ f" {type(prompt)}."
294
+ )
295
+ elif batch_size != len(negative_prompt):
296
+ raise ValueError(
297
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
298
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
299
+ " the batch size of `prompt`."
300
+ )
301
+
302
+ negative_prompt_embeds = self._get_t5_prompt_embeds(
303
+ prompt=negative_prompt,
304
+ num_videos_per_prompt=num_videos_per_prompt,
305
+ max_sequence_length=max_sequence_length,
306
+ device=device,
307
+ dtype=dtype,
308
+ )
309
+
310
+ return prompt_embeds, negative_prompt_embeds
311
+
312
+ def check_inputs(
313
+ self,
314
+ prompt,
315
+ negative_prompt,
316
+ height,
317
+ width,
318
+ prompt_embeds=None,
319
+ negative_prompt_embeds=None,
320
+ callback_on_step_end_tensor_inputs=None,
321
+ video=None,
322
+ mask=None,
323
+ reference_images=None,
324
+ ):
325
+ base = self.vae_scale_factor_spatial * self.transformer.config.patch_size[1]
326
+ if height % base != 0 or width % base != 0:
327
+ raise ValueError(f"`height` and `width` have to be divisible by {base} but are {height} and {width}.")
328
+
329
+ if callback_on_step_end_tensor_inputs is not None and not all(
330
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
331
+ ):
332
+ raise ValueError(
333
+ 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]}"
334
+ )
335
+
336
+ if prompt is not None and prompt_embeds is not None:
337
+ raise ValueError(
338
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
339
+ " only forward one of the two."
340
+ )
341
+ elif negative_prompt is not None and negative_prompt_embeds is not None:
342
+ raise ValueError(
343
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
344
+ " only forward one of the two."
345
+ )
346
+ elif prompt is None and prompt_embeds is None:
347
+ raise ValueError(
348
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
349
+ )
350
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
351
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
352
+ elif negative_prompt is not None and (
353
+ not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
354
+ ):
355
+ raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
356
+
357
+ if video is not None:
358
+ if mask is not None:
359
+ if len(video) != len(mask):
360
+ raise ValueError(
361
+ f"Length of `video` {len(video)} and `mask` {len(mask)} do not match. Please make sure that"
362
+ " they have the same length."
363
+ )
364
+ if reference_images is not None:
365
+ is_pil_image = isinstance(reference_images, PIL.Image.Image)
366
+ is_list_of_pil_images = isinstance(reference_images, list) and all(
367
+ isinstance(ref_img, PIL.Image.Image) for ref_img in reference_images
368
+ )
369
+ is_list_of_list_of_pil_images = isinstance(reference_images, list) and all(
370
+ isinstance(ref_img, list) and all(isinstance(ref_img_, PIL.Image.Image) for ref_img_ in ref_img)
371
+ for ref_img in reference_images
372
+ )
373
+ if not (is_pil_image or is_list_of_pil_images or is_list_of_list_of_pil_images):
374
+ raise ValueError(
375
+ "`reference_images` has to be of type `PIL.Image.Image` or `list` of `PIL.Image.Image`, or "
376
+ "`list` of `list` of `PIL.Image.Image`, but is {type(reference_images)}"
377
+ )
378
+ if is_list_of_list_of_pil_images and len(reference_images) != 1:
379
+ raise ValueError(
380
+ "The pipeline only supports generating one video at a time at the moment. When passing a list "
381
+ "of list of reference images, where the outer list corresponds to the batch size and the inner "
382
+ "list corresponds to list of conditioning images per video, please make sure to only pass "
383
+ "one inner list of reference images (i.e., `[[<image1>, <image2>, ...]]`"
384
+ )
385
+ elif mask is not None:
386
+ raise ValueError("`mask` can only be passed if `video` is passed as well.")
387
+
388
+ def preprocess_conditions(
389
+ self,
390
+ video: Optional[List[PipelineImageInput]] = None,
391
+ mask: Optional[List[PipelineImageInput]] = None,
392
+ reference_images: Optional[Union[PIL.Image.Image, List[PIL.Image.Image], List[List[PIL.Image.Image]]]] = None,
393
+ batch_size: int = 1,
394
+ height: int = 480,
395
+ width: int = 832,
396
+ num_frames: int = 81,
397
+ dtype: Optional[torch.dtype] = None,
398
+ device: Optional[torch.device] = None,
399
+ ):
400
+ if video is not None:
401
+ base = self.vae_scale_factor_spatial * self.transformer.config.patch_size[1]
402
+ video_height, video_width = self.video_processor.get_default_height_width(video[0])
403
+
404
+ if video_height * video_width > height * width:
405
+ scale = min(width / video_width, height / video_height)
406
+ video_height, video_width = int(video_height * scale), int(video_width * scale)
407
+
408
+ if video_height % base != 0 or video_width % base != 0:
409
+ logger.warning(
410
+ f"Video height and width should be divisible by {base}, but got {video_height} and {video_width}. "
411
+ )
412
+ video_height = (video_height // base) * base
413
+ video_width = (video_width // base) * base
414
+
415
+ assert video_height * video_width <= height * width
416
+
417
+ video = self.video_processor.preprocess_video(video, video_height, video_width)
418
+ image_size = (video_height, video_width) # Use the height/width of video (with possible rescaling)
419
+ else:
420
+ video = torch.zeros(batch_size, 3, num_frames, height, width, dtype=dtype, device=device)
421
+ image_size = (height, width) # Use the height/width provider by user
422
+
423
+ if mask is not None:
424
+ mask = self.video_processor.preprocess_video(mask, image_size[0], image_size[1])
425
+ mask = torch.clamp((mask + 1) / 2, min=0, max=1)
426
+ else:
427
+ mask = torch.ones_like(video)
428
+
429
+ video = video.to(dtype=dtype, device=device)
430
+ mask = mask.to(dtype=dtype, device=device)
431
+
432
+ # Make a list of list of images where the outer list corresponds to video batch size and the inner list
433
+ # corresponds to list of conditioning images per video
434
+ if reference_images is None or isinstance(reference_images, PIL.Image.Image):
435
+ reference_images = [[reference_images] for _ in range(video.shape[0])]
436
+ elif isinstance(reference_images, (list, tuple)) and isinstance(next(iter(reference_images)), PIL.Image.Image):
437
+ reference_images = [reference_images]
438
+ elif (
439
+ isinstance(reference_images, (list, tuple))
440
+ and isinstance(next(iter(reference_images)), list)
441
+ and isinstance(next(iter(reference_images[0])), PIL.Image.Image)
442
+ ):
443
+ reference_images = reference_images
444
+ else:
445
+ raise ValueError(
446
+ "`reference_images` has to be of type `PIL.Image.Image` or `list` of `PIL.Image.Image`, or "
447
+ "`list` of `list` of `PIL.Image.Image`, but is {type(reference_images)}"
448
+ )
449
+
450
+ if video.shape[0] != len(reference_images):
451
+ raise ValueError(
452
+ f"Batch size of `video` {video.shape[0]} and length of `reference_images` {len(reference_images)} does not match."
453
+ )
454
+
455
+ ref_images_lengths = [len(reference_images_batch) for reference_images_batch in reference_images]
456
+ if any(l != ref_images_lengths[0] for l in ref_images_lengths):
457
+ raise ValueError(
458
+ f"All batches of `reference_images` should have the same length, but got {ref_images_lengths}. Support for this "
459
+ "may be added in the future."
460
+ )
461
+
462
+ reference_images_preprocessed = []
463
+ for i, reference_images_batch in enumerate(reference_images):
464
+ preprocessed_images = []
465
+ for j, image in enumerate(reference_images_batch):
466
+ if image is None:
467
+ continue
468
+ image = self.video_processor.preprocess(image, None, None)
469
+ img_height, img_width = image.shape[-2:]
470
+ scale = min(image_size[0] / img_height, image_size[1] / img_width)
471
+ new_height, new_width = int(img_height * scale), int(img_width * scale)
472
+ resized_image = torch.nn.functional.interpolate(
473
+ image, size=(new_height, new_width), mode="bilinear", align_corners=False
474
+ ).squeeze(0) # [C, H, W]
475
+ top = (image_size[0] - new_height) // 2
476
+ left = (image_size[1] - new_width) // 2
477
+ canvas = torch.ones(3, *image_size, device=device, dtype=dtype)
478
+ canvas[:, top : top + new_height, left : left + new_width] = resized_image
479
+ preprocessed_images.append(canvas)
480
+ reference_images_preprocessed.append(preprocessed_images)
481
+
482
+ return video, mask, reference_images_preprocessed
483
+
484
+ def prepare_video_latents(
485
+ self,
486
+ video: torch.Tensor,
487
+ mask: torch.Tensor,
488
+ reference_images: Optional[List[List[torch.Tensor]]] = None,
489
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
490
+ device: Optional[torch.device] = None,
491
+ ) -> torch.Tensor:
492
+ device = device or self._execution_device
493
+
494
+ if isinstance(generator, list):
495
+ # TODO: support this
496
+ raise ValueError("Passing a list of generators is not yet supported. This may be supported in the future.")
497
+
498
+ if reference_images is None:
499
+ # For each batch of video, we set no re
500
+ # ference image (as one or more can be passed by user)
501
+ reference_images = [[None] for _ in range(video.shape[0])]
502
+ else:
503
+ if video.shape[0] != len(reference_images):
504
+ raise ValueError(
505
+ f"Batch size of `video` {video.shape[0]} and length of `reference_images` {len(reference_images)} does not match."
506
+ )
507
+
508
+ if video.shape[0] != 1:
509
+ # TODO: support this
510
+ raise ValueError(
511
+ "Generating with more than one video is not yet supported. This may be supported in the future."
512
+ )
513
+
514
+ vae_dtype = self.vae.dtype
515
+ video = video.to(dtype=vae_dtype)
516
+
517
+ latents_mean = torch.tensor(self.vae.config.latents_mean, device=device, dtype=torch.float32).view(
518
+ 1, self.vae.config.z_dim, 1, 1, 1
519
+ )
520
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std, device=device, dtype=torch.float32).view(
521
+ 1, self.vae.config.z_dim, 1, 1, 1
522
+ )
523
+
524
+ if mask is None:
525
+ latents = retrieve_latents(self.vae.encode(video), generator, sample_mode="argmax").unbind(0)
526
+ latents = ((latents.float() - latents_mean) * latents_std).to(vae_dtype)
527
+ else:
528
+ mask = mask.to(dtype=vae_dtype)
529
+ mask = torch.where(mask > 0.5, 1.0, 0.0)
530
+ inactive = video * (1 - mask)
531
+ reactive = video * mask
532
+ inactive = retrieve_latents(self.vae.encode(inactive), generator, sample_mode="argmax")
533
+ reactive = retrieve_latents(self.vae.encode(reactive), generator, sample_mode="argmax")
534
+ inactive = ((inactive.float() - latents_mean) * latents_std).to(vae_dtype)
535
+ reactive = ((reactive.float() - latents_mean) * latents_std).to(vae_dtype)
536
+ latents = torch.cat([inactive, reactive], dim=1)
537
+
538
+ latent_list = []
539
+ for latent, reference_images_batch in zip(latents, reference_images):
540
+ for reference_image in reference_images_batch:
541
+ assert reference_image.ndim == 3
542
+ reference_image = reference_image.to(dtype=vae_dtype)
543
+ reference_image = reference_image[None, :, None, :, :] # [1, C, 1, H, W]
544
+ reference_latent = retrieve_latents(self.vae.encode(reference_image), generator, sample_mode="argmax")
545
+ reference_latent = ((reference_latent.float() - latents_mean) * latents_std).to(vae_dtype)
546
+ reference_latent = reference_latent.squeeze(0) # [C, 1, H, W]
547
+ reference_latent = torch.cat([reference_latent, torch.zeros_like(reference_latent)], dim=0)
548
+ latent = torch.cat([reference_latent.squeeze(0), latent], dim=1)
549
+ latent_list.append(latent)
550
+ return torch.stack(latent_list)
551
+
552
+ def prepare_masks(
553
+ self,
554
+ mask: torch.Tensor,
555
+ reference_images: Optional[List[torch.Tensor]] = None,
556
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
557
+ ) -> torch.Tensor:
558
+ if isinstance(generator, list):
559
+ # TODO: support this
560
+ raise ValueError("Passing a list of generators is not yet supported. This may be supported in the future.")
561
+
562
+ if reference_images is None:
563
+ # For each batch of video, we set no reference image (as one or more can be passed by user)
564
+ reference_images = [[None] for _ in range(mask.shape[0])]
565
+ else:
566
+ if mask.shape[0] != len(reference_images):
567
+ raise ValueError(
568
+ f"Batch size of `mask` {mask.shape[0]} and length of `reference_images` {len(reference_images)} does not match."
569
+ )
570
+
571
+ if mask.shape[0] != 1:
572
+ # TODO: support this
573
+ raise ValueError(
574
+ "Generating with more than one video is not yet supported. This may be supported in the future."
575
+ )
576
+
577
+ transformer_patch_size = self.transformer.config.patch_size[1]
578
+
579
+ mask_list = []
580
+ for mask_, reference_images_batch in zip(mask, reference_images):
581
+ num_channels, num_frames, height, width = mask_.shape
582
+ new_num_frames = (num_frames + self.vae_scale_factor_temporal - 1) // self.vae_scale_factor_temporal
583
+ new_height = height // (self.vae_scale_factor_spatial * transformer_patch_size) * transformer_patch_size
584
+ new_width = width // (self.vae_scale_factor_spatial * transformer_patch_size) * transformer_patch_size
585
+ mask_ = mask_[0, :, :, :]
586
+ mask_ = mask_.view(
587
+ num_frames, new_height, self.vae_scale_factor_spatial, new_width, self.vae_scale_factor_spatial
588
+ )
589
+ mask_ = mask_.permute(2, 4, 0, 1, 3).flatten(0, 1) # [8x8, num_frames, new_height, new_width]
590
+ mask_ = torch.nn.functional.interpolate(
591
+ mask_.unsqueeze(0), size=(new_num_frames, new_height, new_width), mode="nearest-exact"
592
+ ).squeeze(0)
593
+ num_ref_images = len(reference_images_batch)
594
+ if num_ref_images > 0:
595
+ mask_padding = torch.zeros_like(mask_[:, :num_ref_images, :, :])
596
+ mask_ = torch.cat([mask_padding, mask_], dim=1)
597
+ mask_list.append(mask_)
598
+ return torch.stack(mask_list)
599
+
600
+ def prepare_latents(
601
+ self,
602
+ batch_size: int,
603
+ num_channels_latents: int = 16,
604
+ height: int = 480,
605
+ width: int = 832,
606
+ num_frames: int = 81,
607
+ dtype: Optional[torch.dtype] = None,
608
+ device: Optional[torch.device] = None,
609
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
610
+ latents: Optional[torch.Tensor] = None,
611
+ ) -> torch.Tensor:
612
+ if latents is not None:
613
+ return latents.to(device=device, dtype=dtype)
614
+
615
+ num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
616
+ shape = (
617
+ batch_size,
618
+ num_channels_latents,
619
+ num_latent_frames,
620
+ int(height) // self.vae_scale_factor_spatial,
621
+ int(width) // self.vae_scale_factor_spatial,
622
+ )
623
+ if isinstance(generator, list) and len(generator) != batch_size:
624
+ raise ValueError(
625
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
626
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
627
+ )
628
+
629
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
630
+ return latents
631
+
632
+ @property
633
+ def guidance_scale(self):
634
+ return self._guidance_scale
635
+
636
+ @property
637
+ def do_classifier_free_guidance(self):
638
+ return self._guidance_scale > 1.0
639
+
640
+ @property
641
+ def num_timesteps(self):
642
+ return self._num_timesteps
643
+
644
+ @property
645
+ def current_timestep(self):
646
+ return self._current_timestep
647
+
648
+ @property
649
+ def interrupt(self):
650
+ return self._interrupt
651
+
652
+ @property
653
+ def attention_kwargs(self):
654
+ return self._attention_kwargs
655
+
656
+ @torch.no_grad()
657
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
658
+ def __call__(
659
+ self,
660
+ prompt: Union[str, List[str]] = None,
661
+ negative_prompt: Union[str, List[str]] = None,
662
+ video: Optional[List[PipelineImageInput]] = None,
663
+ mask: Optional[List[PipelineImageInput]] = None,
664
+ reference_images: Optional[List[PipelineImageInput]] = None,
665
+ conditioning_scale: Union[float, List[float], torch.Tensor] = 1.0,
666
+ height: int = 480,
667
+ width: int = 832,
668
+ num_frames: int = 81,
669
+ num_inference_steps: int = 50,
670
+ guidance_scale: float = 5.0,
671
+ num_videos_per_prompt: Optional[int] = 1,
672
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
673
+ latents: Optional[torch.Tensor] = None,
674
+ prompt_embeds: Optional[torch.Tensor] = None,
675
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
676
+ output_type: Optional[str] = "np",
677
+ return_dict: bool = True,
678
+ attention_kwargs: Optional[Dict[str, Any]] = None,
679
+ callback_on_step_end: Optional[
680
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
681
+ ] = None,
682
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
683
+ max_sequence_length: int = 512,
684
+ ):
685
+ r"""
686
+ The call function to the pipeline for generation.
687
+
688
+ Args:
689
+ prompt (`str` or `List[str]`, *optional*):
690
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`
691
+ instead.
692
+ negative_prompt (`str` or `List[str]`, *optional*):
693
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
694
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
695
+ less than `1`).
696
+ video (`List[PIL.Image.Image]`, *optional*):
697
+ The input video or videos to be used as a starting point for the generation. The video should be a list
698
+ of PIL images, a numpy array, or a torch tensor. Currently, the pipeline only supports generating one
699
+ video at a time.
700
+ mask (`List[PIL.Image.Image]`, *optional*):
701
+ The input mask defines which video regions to condition on and which to generate. Black areas in the
702
+ mask indicate conditioning regions, while white areas indicate regions for generation. The mask should
703
+ be a list of PIL images, a numpy array, or a torch tensor. Currently supports generating a single video
704
+ at a time.
705
+ reference_images (`List[PIL.Image.Image]`, *optional*):
706
+ A list of one or more reference images as extra conditioning for the generation. For example, if you
707
+ are trying to inpaint a video to change the character, you can pass reference images of the new
708
+ character here. Refer to the Diffusers [examples](https://github.com/huggingface/diffusers/pull/11582)
709
+ and original [user
710
+ guide](https://github.com/ali-vilab/VACE/blob/0897c6d055d7d9ea9e191dce763006664d9780f8/UserGuide.md)
711
+ for a full list of supported tasks and use cases.
712
+ conditioning_scale (`float`, `List[float]`, `torch.Tensor`, defaults to `1.0`):
713
+ The conditioning scale to be applied when adding the control conditioning latent stream to the
714
+ denoising latent stream in each control layer of the model. If a float is provided, it will be applied
715
+ uniformly to all layers. If a list or tensor is provided, it should have the same length as the number
716
+ of control layers in the model (`len(transformer.config.vace_layers)`).
717
+ height (`int`, defaults to `480`):
718
+ The height in pixels of the generated image.
719
+ width (`int`, defaults to `832`):
720
+ The width in pixels of the generated image.
721
+ num_frames (`int`, defaults to `81`):
722
+ The number of frames in the generated video.
723
+ num_inference_steps (`int`, defaults to `50`):
724
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
725
+ expense of slower inference.
726
+ guidance_scale (`float`, defaults to `5.0`):
727
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
728
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
729
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
730
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
731
+ usually at the expense of lower image quality.
732
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
733
+ The number of images to generate per prompt.
734
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
735
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
736
+ generation deterministic.
737
+ latents (`torch.Tensor`, *optional*):
738
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
739
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
740
+ tensor is generated by sampling using the supplied random `generator`.
741
+ prompt_embeds (`torch.Tensor`, *optional*):
742
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
743
+ provided, text embeddings are generated from the `prompt` input argument.
744
+ output_type (`str`, *optional*, defaults to `"np"`):
745
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
746
+ return_dict (`bool`, *optional*, defaults to `True`):
747
+ Whether or not to return a [`WanPipelineOutput`] instead of a plain tuple.
748
+ attention_kwargs (`dict`, *optional*):
749
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
750
+ `self.processor` in
751
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
752
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
753
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
754
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
755
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
756
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
757
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
758
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
759
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
760
+ `._callback_tensor_inputs` attribute of your pipeline class.
761
+ max_sequence_length (`int`, defaults to `512`):
762
+ The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
763
+ truncated. If the prompt is shorter, it will be padded to this length.
764
+
765
+ Examples:
766
+
767
+ Returns:
768
+ [`~WanPipelineOutput`] or `tuple`:
769
+ If `return_dict` is `True`, [`WanPipelineOutput`] is returned, otherwise a `tuple` is returned where
770
+ the first element is a list with the generated images and the second element is a list of `bool`s
771
+ indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
772
+ """
773
+
774
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
775
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
776
+
777
+ # Simplification of implementation for now
778
+ if not isinstance(prompt, str):
779
+ raise ValueError("Passing a list of prompts is not yet supported. This may be supported in the future.")
780
+ if num_videos_per_prompt != 1:
781
+ raise ValueError(
782
+ "Generating multiple videos per prompt is not yet supported. This may be supported in the future."
783
+ )
784
+
785
+ # 1. Check inputs. Raise error if not correct
786
+ self.check_inputs(
787
+ prompt,
788
+ negative_prompt,
789
+ height,
790
+ width,
791
+ prompt_embeds,
792
+ negative_prompt_embeds,
793
+ callback_on_step_end_tensor_inputs,
794
+ video,
795
+ mask,
796
+ reference_images,
797
+ )
798
+
799
+ if num_frames % self.vae_scale_factor_temporal != 1:
800
+ logger.warning(
801
+ f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
802
+ )
803
+ num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
804
+ num_frames = max(num_frames, 1)
805
+
806
+ self._guidance_scale = guidance_scale
807
+ self._attention_kwargs = attention_kwargs
808
+ self._current_timestep = None
809
+ self._interrupt = False
810
+
811
+ device = self._execution_device
812
+
813
+ # 2. Define call parameters
814
+ if prompt is not None and isinstance(prompt, str):
815
+ batch_size = 1
816
+ elif prompt is not None and isinstance(prompt, list):
817
+ batch_size = len(prompt)
818
+ else:
819
+ batch_size = prompt_embeds.shape[0]
820
+
821
+ vae_dtype = self.vae.dtype
822
+ transformer_dtype = self.transformer.dtype
823
+
824
+ if isinstance(conditioning_scale, (int, float)):
825
+ conditioning_scale = [conditioning_scale] * len(self.transformer.config.vace_layers)
826
+ if isinstance(conditioning_scale, list):
827
+ if len(conditioning_scale) != len(self.transformer.config.vace_layers):
828
+ raise ValueError(
829
+ f"Length of `conditioning_scale` {len(conditioning_scale)} does not match number of layers {len(self.transformer.config.vace_layers)}."
830
+ )
831
+ conditioning_scale = torch.tensor(conditioning_scale)
832
+ if isinstance(conditioning_scale, torch.Tensor):
833
+ if conditioning_scale.size(0) != len(self.transformer.config.vace_layers):
834
+ raise ValueError(
835
+ f"Length of `conditioning_scale` {conditioning_scale.size(0)} does not match number of layers {len(self.transformer.config.vace_layers)}."
836
+ )
837
+ conditioning_scale = conditioning_scale.to(device=device, dtype=transformer_dtype)
838
+
839
+ # 3. Encode input prompt
840
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
841
+ prompt=prompt,
842
+ negative_prompt=negative_prompt,
843
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
844
+ num_videos_per_prompt=num_videos_per_prompt,
845
+ prompt_embeds=prompt_embeds,
846
+ negative_prompt_embeds=negative_prompt_embeds,
847
+ max_sequence_length=max_sequence_length,
848
+ device=device,
849
+ )
850
+
851
+ prompt_embeds = prompt_embeds.to(transformer_dtype)
852
+ if negative_prompt_embeds is not None:
853
+ negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
854
+
855
+ # 4. Prepare timesteps
856
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
857
+ timesteps = self.scheduler.timesteps
858
+
859
+ # 5. Prepare latent variables
860
+ video, mask, reference_images = self.preprocess_conditions(
861
+ video,
862
+ mask,
863
+ reference_images,
864
+ batch_size,
865
+ height,
866
+ width,
867
+ num_frames,
868
+ torch.float32,
869
+ device,
870
+ )
871
+ num_reference_images = len(reference_images[0])
872
+
873
+ conditioning_latents = self.prepare_video_latents(video, mask, reference_images, generator, device)
874
+ mask = self.prepare_masks(mask, reference_images, generator)
875
+ conditioning_latents = torch.cat([conditioning_latents, mask], dim=1)
876
+ conditioning_latents = conditioning_latents.to(transformer_dtype)
877
+
878
+ num_channels_latents = self.transformer.config.in_channels
879
+ latents = self.prepare_latents(
880
+ batch_size * num_videos_per_prompt,
881
+ num_channels_latents,
882
+ height,
883
+ width,
884
+ num_frames + num_reference_images * self.vae_scale_factor_temporal,
885
+ torch.float32,
886
+ device,
887
+ generator,
888
+ latents,
889
+ )
890
+
891
+ if conditioning_latents.shape[2] != latents.shape[2]:
892
+ logger.warning(
893
+ "The number of frames in the conditioning latents does not match the number of frames to be generated. Generation quality may be affected."
894
+ )
895
+
896
+ # 6. Denoising loop
897
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
898
+ self._num_timesteps = len(timesteps)
899
+
900
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
901
+ for i, t in enumerate(timesteps):
902
+ if self.interrupt:
903
+ continue
904
+
905
+ self._current_timestep = t
906
+ latent_model_input = latents.to(transformer_dtype)
907
+ timestep = t.expand(latents.shape[0])
908
+
909
+ noise_pred = self.transformer(
910
+ hidden_states=latent_model_input,
911
+ timestep=timestep,
912
+ encoder_hidden_states=prompt_embeds,
913
+ control_hidden_states=conditioning_latents,
914
+ control_hidden_states_scale=conditioning_scale,
915
+ attention_kwargs=attention_kwargs,
916
+ return_dict=False,
917
+ )[0]
918
+
919
+ if self.do_classifier_free_guidance:
920
+ noise_uncond = self.transformer(
921
+ hidden_states=latent_model_input,
922
+ timestep=timestep,
923
+ encoder_hidden_states=negative_prompt_embeds,
924
+ control_hidden_states=conditioning_latents,
925
+ control_hidden_states_scale=conditioning_scale,
926
+ attention_kwargs=attention_kwargs,
927
+ return_dict=False,
928
+ )[0]
929
+ noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)
930
+
931
+ # compute the previous noisy sample x_t -> x_t-1
932
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
933
+
934
+ if callback_on_step_end is not None:
935
+ callback_kwargs = {}
936
+ for k in callback_on_step_end_tensor_inputs:
937
+ callback_kwargs[k] = locals()[k]
938
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
939
+
940
+ latents = callback_outputs.pop("latents", latents)
941
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
942
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
943
+
944
+ # call the callback, if provided
945
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
946
+ progress_bar.update()
947
+
948
+ if XLA_AVAILABLE:
949
+ xm.mark_step()
950
+
951
+ self._current_timestep = None
952
+
953
+ if not output_type == "latent":
954
+ latents = latents[:, :, num_reference_images:]
955
+ latents = latents.to(vae_dtype)
956
+ latents_mean = (
957
+ torch.tensor(self.vae.config.latents_mean)
958
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
959
+ .to(latents.device, latents.dtype)
960
+ )
961
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
962
+ latents.device, latents.dtype
963
+ )
964
+ latents = latents / latents_std + latents_mean
965
+ video = self.vae.decode(latents, return_dict=False)[0]
966
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
967
+ else:
968
+ video = latents
969
+
970
+ # Offload all models
971
+ self.maybe_free_model_hooks()
972
+
973
+ if not return_dict:
974
+ return (video,)
975
+
976
+ return WanPipelineOutput(frames=video)