diffusers 0.32.1__py3-none-any.whl → 0.33.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (389) hide show
  1. diffusers/__init__.py +186 -3
  2. diffusers/configuration_utils.py +40 -12
  3. diffusers/dependency_versions_table.py +9 -2
  4. diffusers/hooks/__init__.py +9 -0
  5. diffusers/hooks/faster_cache.py +653 -0
  6. diffusers/hooks/group_offloading.py +793 -0
  7. diffusers/hooks/hooks.py +236 -0
  8. diffusers/hooks/layerwise_casting.py +245 -0
  9. diffusers/hooks/pyramid_attention_broadcast.py +311 -0
  10. diffusers/loaders/__init__.py +6 -0
  11. diffusers/loaders/ip_adapter.py +38 -30
  12. diffusers/loaders/lora_base.py +198 -28
  13. diffusers/loaders/lora_conversion_utils.py +679 -44
  14. diffusers/loaders/lora_pipeline.py +1963 -801
  15. diffusers/loaders/peft.py +169 -84
  16. diffusers/loaders/single_file.py +17 -2
  17. diffusers/loaders/single_file_model.py +53 -5
  18. diffusers/loaders/single_file_utils.py +653 -75
  19. diffusers/loaders/textual_inversion.py +9 -9
  20. diffusers/loaders/transformer_flux.py +8 -9
  21. diffusers/loaders/transformer_sd3.py +120 -39
  22. diffusers/loaders/unet.py +22 -32
  23. diffusers/models/__init__.py +22 -0
  24. diffusers/models/activations.py +9 -9
  25. diffusers/models/attention.py +0 -1
  26. diffusers/models/attention_processor.py +163 -25
  27. diffusers/models/auto_model.py +169 -0
  28. diffusers/models/autoencoders/__init__.py +2 -0
  29. diffusers/models/autoencoders/autoencoder_asym_kl.py +2 -0
  30. diffusers/models/autoencoders/autoencoder_dc.py +106 -4
  31. diffusers/models/autoencoders/autoencoder_kl.py +0 -4
  32. diffusers/models/autoencoders/autoencoder_kl_allegro.py +5 -23
  33. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +17 -55
  34. diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py +17 -97
  35. diffusers/models/autoencoders/autoencoder_kl_ltx.py +326 -107
  36. diffusers/models/autoencoders/autoencoder_kl_magvit.py +1094 -0
  37. diffusers/models/autoencoders/autoencoder_kl_mochi.py +21 -56
  38. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +11 -42
  39. diffusers/models/autoencoders/autoencoder_kl_wan.py +855 -0
  40. diffusers/models/autoencoders/autoencoder_oobleck.py +1 -0
  41. diffusers/models/autoencoders/autoencoder_tiny.py +0 -4
  42. diffusers/models/autoencoders/consistency_decoder_vae.py +3 -1
  43. diffusers/models/autoencoders/vae.py +31 -141
  44. diffusers/models/autoencoders/vq_model.py +3 -0
  45. diffusers/models/cache_utils.py +108 -0
  46. diffusers/models/controlnets/__init__.py +1 -0
  47. diffusers/models/controlnets/controlnet.py +3 -8
  48. diffusers/models/controlnets/controlnet_flux.py +14 -42
  49. diffusers/models/controlnets/controlnet_sd3.py +58 -34
  50. diffusers/models/controlnets/controlnet_sparsectrl.py +4 -7
  51. diffusers/models/controlnets/controlnet_union.py +27 -18
  52. diffusers/models/controlnets/controlnet_xs.py +7 -46
  53. diffusers/models/controlnets/multicontrolnet_union.py +196 -0
  54. diffusers/models/embeddings.py +18 -7
  55. diffusers/models/model_loading_utils.py +122 -80
  56. diffusers/models/modeling_flax_pytorch_utils.py +1 -1
  57. diffusers/models/modeling_flax_utils.py +1 -1
  58. diffusers/models/modeling_pytorch_flax_utils.py +1 -1
  59. diffusers/models/modeling_utils.py +617 -272
  60. diffusers/models/normalization.py +67 -14
  61. diffusers/models/resnet.py +1 -1
  62. diffusers/models/transformers/__init__.py +6 -0
  63. diffusers/models/transformers/auraflow_transformer_2d.py +9 -35
  64. diffusers/models/transformers/cogvideox_transformer_3d.py +13 -24
  65. diffusers/models/transformers/consisid_transformer_3d.py +789 -0
  66. diffusers/models/transformers/dit_transformer_2d.py +5 -19
  67. diffusers/models/transformers/hunyuan_transformer_2d.py +4 -3
  68. diffusers/models/transformers/latte_transformer_3d.py +20 -15
  69. diffusers/models/transformers/lumina_nextdit2d.py +3 -1
  70. diffusers/models/transformers/pixart_transformer_2d.py +4 -19
  71. diffusers/models/transformers/prior_transformer.py +5 -1
  72. diffusers/models/transformers/sana_transformer.py +144 -40
  73. diffusers/models/transformers/stable_audio_transformer.py +5 -20
  74. diffusers/models/transformers/transformer_2d.py +7 -22
  75. diffusers/models/transformers/transformer_allegro.py +9 -17
  76. diffusers/models/transformers/transformer_cogview3plus.py +6 -17
  77. diffusers/models/transformers/transformer_cogview4.py +462 -0
  78. diffusers/models/transformers/transformer_easyanimate.py +527 -0
  79. diffusers/models/transformers/transformer_flux.py +68 -110
  80. diffusers/models/transformers/transformer_hunyuan_video.py +409 -49
  81. diffusers/models/transformers/transformer_ltx.py +53 -35
  82. diffusers/models/transformers/transformer_lumina2.py +548 -0
  83. diffusers/models/transformers/transformer_mochi.py +6 -17
  84. diffusers/models/transformers/transformer_omnigen.py +469 -0
  85. diffusers/models/transformers/transformer_sd3.py +56 -86
  86. diffusers/models/transformers/transformer_temporal.py +5 -11
  87. diffusers/models/transformers/transformer_wan.py +469 -0
  88. diffusers/models/unets/unet_1d.py +3 -1
  89. diffusers/models/unets/unet_2d.py +21 -20
  90. diffusers/models/unets/unet_2d_blocks.py +19 -243
  91. diffusers/models/unets/unet_2d_condition.py +4 -6
  92. diffusers/models/unets/unet_3d_blocks.py +14 -127
  93. diffusers/models/unets/unet_3d_condition.py +8 -12
  94. diffusers/models/unets/unet_i2vgen_xl.py +5 -13
  95. diffusers/models/unets/unet_kandinsky3.py +0 -4
  96. diffusers/models/unets/unet_motion_model.py +20 -114
  97. diffusers/models/unets/unet_spatio_temporal_condition.py +7 -8
  98. diffusers/models/unets/unet_stable_cascade.py +8 -35
  99. diffusers/models/unets/uvit_2d.py +1 -4
  100. diffusers/optimization.py +2 -2
  101. diffusers/pipelines/__init__.py +57 -8
  102. diffusers/pipelines/allegro/pipeline_allegro.py +22 -2
  103. diffusers/pipelines/amused/pipeline_amused.py +15 -2
  104. diffusers/pipelines/amused/pipeline_amused_img2img.py +15 -2
  105. diffusers/pipelines/amused/pipeline_amused_inpaint.py +15 -2
  106. diffusers/pipelines/animatediff/pipeline_animatediff.py +15 -2
  107. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +15 -3
  108. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +24 -4
  109. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +15 -2
  110. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +16 -4
  111. diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +16 -4
  112. diffusers/pipelines/audioldm/pipeline_audioldm.py +13 -2
  113. diffusers/pipelines/audioldm2/modeling_audioldm2.py +13 -68
  114. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +39 -9
  115. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +63 -7
  116. diffusers/pipelines/auto_pipeline.py +35 -14
  117. diffusers/pipelines/blip_diffusion/blip_image_processing.py +1 -1
  118. diffusers/pipelines/blip_diffusion/modeling_blip2.py +5 -8
  119. diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +12 -0
  120. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +22 -6
  121. diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +22 -6
  122. diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +22 -5
  123. diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +22 -6
  124. diffusers/pipelines/cogview3/pipeline_cogview3plus.py +12 -4
  125. diffusers/pipelines/cogview4/__init__.py +49 -0
  126. diffusers/pipelines/cogview4/pipeline_cogview4.py +684 -0
  127. diffusers/pipelines/cogview4/pipeline_cogview4_control.py +732 -0
  128. diffusers/pipelines/cogview4/pipeline_output.py +21 -0
  129. diffusers/pipelines/consisid/__init__.py +49 -0
  130. diffusers/pipelines/consisid/consisid_utils.py +357 -0
  131. diffusers/pipelines/consisid/pipeline_consisid.py +974 -0
  132. diffusers/pipelines/consisid/pipeline_output.py +20 -0
  133. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +11 -0
  134. diffusers/pipelines/controlnet/pipeline_controlnet.py +6 -5
  135. diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +13 -0
  136. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +17 -5
  137. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +31 -12
  138. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +26 -7
  139. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +20 -3
  140. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +22 -3
  141. diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +26 -25
  142. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +224 -109
  143. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +25 -29
  144. diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +7 -4
  145. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +3 -5
  146. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +121 -10
  147. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +122 -11
  148. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +12 -1
  149. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +20 -3
  150. diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +14 -2
  151. diffusers/pipelines/ddim/pipeline_ddim.py +14 -1
  152. diffusers/pipelines/ddpm/pipeline_ddpm.py +15 -1
  153. diffusers/pipelines/deepfloyd_if/pipeline_if.py +12 -0
  154. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +12 -0
  155. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +14 -1
  156. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +12 -0
  157. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +14 -1
  158. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +14 -1
  159. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +11 -7
  160. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +11 -7
  161. diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +1 -1
  162. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +10 -6
  163. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_onnx_stable_diffusion_inpaint_legacy.py +2 -2
  164. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +11 -7
  165. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +1 -1
  166. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +1 -1
  167. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +1 -1
  168. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +10 -105
  169. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py +1 -1
  170. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +1 -1
  171. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +1 -1
  172. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +1 -1
  173. diffusers/pipelines/dit/pipeline_dit.py +15 -2
  174. diffusers/pipelines/easyanimate/__init__.py +52 -0
  175. diffusers/pipelines/easyanimate/pipeline_easyanimate.py +770 -0
  176. diffusers/pipelines/easyanimate/pipeline_easyanimate_control.py +994 -0
  177. diffusers/pipelines/easyanimate/pipeline_easyanimate_inpaint.py +1234 -0
  178. diffusers/pipelines/easyanimate/pipeline_output.py +20 -0
  179. diffusers/pipelines/flux/pipeline_flux.py +53 -21
  180. diffusers/pipelines/flux/pipeline_flux_control.py +9 -12
  181. diffusers/pipelines/flux/pipeline_flux_control_img2img.py +6 -10
  182. diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +8 -10
  183. diffusers/pipelines/flux/pipeline_flux_controlnet.py +185 -13
  184. diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +8 -10
  185. diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +16 -16
  186. diffusers/pipelines/flux/pipeline_flux_fill.py +107 -39
  187. diffusers/pipelines/flux/pipeline_flux_img2img.py +193 -15
  188. diffusers/pipelines/flux/pipeline_flux_inpaint.py +199 -19
  189. diffusers/pipelines/free_noise_utils.py +3 -3
  190. diffusers/pipelines/hunyuan_video/__init__.py +4 -0
  191. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_skyreels_image2video.py +804 -0
  192. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +90 -23
  193. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video_image2video.py +924 -0
  194. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +3 -5
  195. diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +13 -1
  196. diffusers/pipelines/kandinsky/pipeline_kandinsky.py +12 -0
  197. diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +1 -1
  198. diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +12 -0
  199. diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +13 -1
  200. diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +12 -0
  201. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +12 -1
  202. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +13 -0
  203. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +12 -0
  204. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +12 -1
  205. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +12 -1
  206. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +12 -0
  207. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +12 -0
  208. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +12 -0
  209. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +12 -0
  210. diffusers/pipelines/kolors/pipeline_kolors.py +10 -8
  211. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +6 -4
  212. diffusers/pipelines/kolors/text_encoder.py +7 -34
  213. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +12 -1
  214. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +13 -1
  215. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +14 -13
  216. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion_superresolution.py +12 -1
  217. diffusers/pipelines/latte/pipeline_latte.py +36 -7
  218. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +67 -13
  219. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +60 -15
  220. diffusers/pipelines/ltx/__init__.py +2 -0
  221. diffusers/pipelines/ltx/pipeline_ltx.py +25 -13
  222. diffusers/pipelines/ltx/pipeline_ltx_condition.py +1194 -0
  223. diffusers/pipelines/ltx/pipeline_ltx_image2video.py +31 -17
  224. diffusers/pipelines/lumina/__init__.py +2 -2
  225. diffusers/pipelines/lumina/pipeline_lumina.py +83 -20
  226. diffusers/pipelines/lumina2/__init__.py +48 -0
  227. diffusers/pipelines/lumina2/pipeline_lumina2.py +790 -0
  228. diffusers/pipelines/marigold/__init__.py +2 -0
  229. diffusers/pipelines/marigold/marigold_image_processing.py +127 -14
  230. diffusers/pipelines/marigold/pipeline_marigold_depth.py +31 -16
  231. diffusers/pipelines/marigold/pipeline_marigold_intrinsics.py +721 -0
  232. diffusers/pipelines/marigold/pipeline_marigold_normals.py +31 -16
  233. diffusers/pipelines/mochi/pipeline_mochi.py +14 -18
  234. diffusers/pipelines/musicldm/pipeline_musicldm.py +16 -1
  235. diffusers/pipelines/omnigen/__init__.py +50 -0
  236. diffusers/pipelines/omnigen/pipeline_omnigen.py +512 -0
  237. diffusers/pipelines/omnigen/processor_omnigen.py +327 -0
  238. diffusers/pipelines/onnx_utils.py +5 -3
  239. diffusers/pipelines/pag/pag_utils.py +1 -1
  240. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +12 -1
  241. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +15 -4
  242. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +20 -3
  243. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +20 -3
  244. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +1 -3
  245. diffusers/pipelines/pag/pipeline_pag_kolors.py +6 -4
  246. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +16 -3
  247. diffusers/pipelines/pag/pipeline_pag_sana.py +65 -8
  248. diffusers/pipelines/pag/pipeline_pag_sd.py +23 -7
  249. diffusers/pipelines/pag/pipeline_pag_sd_3.py +3 -5
  250. diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +3 -5
  251. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +13 -1
  252. diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +23 -7
  253. diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +26 -10
  254. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +12 -4
  255. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +7 -3
  256. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +10 -6
  257. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +13 -3
  258. diffusers/pipelines/pia/pipeline_pia.py +13 -1
  259. diffusers/pipelines/pipeline_flax_utils.py +7 -7
  260. diffusers/pipelines/pipeline_loading_utils.py +193 -83
  261. diffusers/pipelines/pipeline_utils.py +221 -106
  262. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +17 -5
  263. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +17 -4
  264. diffusers/pipelines/sana/__init__.py +2 -0
  265. diffusers/pipelines/sana/pipeline_sana.py +183 -58
  266. diffusers/pipelines/sana/pipeline_sana_sprint.py +889 -0
  267. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +12 -2
  268. diffusers/pipelines/shap_e/pipeline_shap_e.py +12 -0
  269. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +12 -0
  270. diffusers/pipelines/shap_e/renderer.py +6 -6
  271. diffusers/pipelines/stable_audio/pipeline_stable_audio.py +1 -1
  272. diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +15 -4
  273. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +12 -8
  274. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +12 -1
  275. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +3 -2
  276. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +14 -10
  277. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_img2img.py +3 -3
  278. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_inpaint.py +14 -10
  279. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +2 -2
  280. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +4 -3
  281. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +5 -4
  282. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +2 -2
  283. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +18 -13
  284. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +30 -8
  285. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +24 -10
  286. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +28 -12
  287. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +39 -18
  288. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +17 -6
  289. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +13 -3
  290. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +20 -3
  291. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +14 -2
  292. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +13 -1
  293. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +16 -17
  294. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +136 -18
  295. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +150 -21
  296. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +15 -3
  297. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +26 -11
  298. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +15 -3
  299. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +22 -4
  300. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +30 -13
  301. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +12 -4
  302. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +15 -3
  303. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +15 -3
  304. diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +26 -12
  305. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +16 -4
  306. diffusers/pipelines/stable_diffusion_xl/pipeline_flax_stable_diffusion_xl.py +1 -1
  307. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +12 -4
  308. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +7 -3
  309. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +10 -6
  310. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +11 -4
  311. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +13 -2
  312. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +18 -4
  313. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +26 -5
  314. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +13 -1
  315. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +13 -1
  316. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +28 -6
  317. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +26 -4
  318. diffusers/pipelines/transformers_loading_utils.py +121 -0
  319. diffusers/pipelines/unclip/pipeline_unclip.py +11 -1
  320. diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +11 -1
  321. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +19 -2
  322. diffusers/pipelines/wan/__init__.py +51 -0
  323. diffusers/pipelines/wan/pipeline_output.py +20 -0
  324. diffusers/pipelines/wan/pipeline_wan.py +593 -0
  325. diffusers/pipelines/wan/pipeline_wan_i2v.py +722 -0
  326. diffusers/pipelines/wan/pipeline_wan_video2video.py +725 -0
  327. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +7 -31
  328. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +12 -1
  329. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +12 -1
  330. diffusers/quantizers/auto.py +5 -1
  331. diffusers/quantizers/base.py +5 -9
  332. diffusers/quantizers/bitsandbytes/bnb_quantizer.py +41 -29
  333. diffusers/quantizers/bitsandbytes/utils.py +30 -20
  334. diffusers/quantizers/gguf/gguf_quantizer.py +1 -0
  335. diffusers/quantizers/gguf/utils.py +4 -2
  336. diffusers/quantizers/quantization_config.py +59 -4
  337. diffusers/quantizers/quanto/__init__.py +1 -0
  338. diffusers/quantizers/quanto/quanto_quantizer.py +177 -0
  339. diffusers/quantizers/quanto/utils.py +60 -0
  340. diffusers/quantizers/torchao/__init__.py +1 -1
  341. diffusers/quantizers/torchao/torchao_quantizer.py +47 -2
  342. diffusers/schedulers/__init__.py +2 -1
  343. diffusers/schedulers/scheduling_consistency_models.py +1 -2
  344. diffusers/schedulers/scheduling_ddim_inverse.py +1 -1
  345. diffusers/schedulers/scheduling_ddpm.py +2 -3
  346. diffusers/schedulers/scheduling_ddpm_parallel.py +1 -2
  347. diffusers/schedulers/scheduling_dpmsolver_multistep.py +12 -4
  348. diffusers/schedulers/scheduling_edm_euler.py +45 -10
  349. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +116 -28
  350. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +7 -6
  351. diffusers/schedulers/scheduling_heun_discrete.py +1 -1
  352. diffusers/schedulers/scheduling_lcm.py +1 -2
  353. diffusers/schedulers/scheduling_lms_discrete.py +1 -1
  354. diffusers/schedulers/scheduling_repaint.py +5 -1
  355. diffusers/schedulers/scheduling_scm.py +265 -0
  356. diffusers/schedulers/scheduling_tcd.py +1 -2
  357. diffusers/schedulers/scheduling_utils.py +2 -1
  358. diffusers/training_utils.py +14 -7
  359. diffusers/utils/__init__.py +10 -2
  360. diffusers/utils/constants.py +13 -1
  361. diffusers/utils/deprecation_utils.py +1 -1
  362. diffusers/utils/dummy_bitsandbytes_objects.py +17 -0
  363. diffusers/utils/dummy_gguf_objects.py +17 -0
  364. diffusers/utils/dummy_optimum_quanto_objects.py +17 -0
  365. diffusers/utils/dummy_pt_objects.py +233 -0
  366. diffusers/utils/dummy_torch_and_transformers_and_opencv_objects.py +17 -0
  367. diffusers/utils/dummy_torch_and_transformers_objects.py +270 -0
  368. diffusers/utils/dummy_torchao_objects.py +17 -0
  369. diffusers/utils/dynamic_modules_utils.py +1 -1
  370. diffusers/utils/export_utils.py +28 -3
  371. diffusers/utils/hub_utils.py +52 -102
  372. diffusers/utils/import_utils.py +121 -221
  373. diffusers/utils/loading_utils.py +14 -1
  374. diffusers/utils/logging.py +1 -2
  375. diffusers/utils/peft_utils.py +6 -14
  376. diffusers/utils/remote_utils.py +425 -0
  377. diffusers/utils/source_code_parsing_utils.py +52 -0
  378. diffusers/utils/state_dict_utils.py +15 -1
  379. diffusers/utils/testing_utils.py +243 -13
  380. diffusers/utils/torch_utils.py +10 -0
  381. diffusers/utils/typing_utils.py +91 -0
  382. diffusers/video_processor.py +1 -1
  383. {diffusers-0.32.1.dist-info → diffusers-0.33.0.dist-info}/METADATA +76 -44
  384. diffusers-0.33.0.dist-info/RECORD +608 -0
  385. {diffusers-0.32.1.dist-info → diffusers-0.33.0.dist-info}/WHEEL +1 -1
  386. diffusers-0.32.1.dist-info/RECORD +0 -550
  387. {diffusers-0.32.1.dist-info → diffusers-0.33.0.dist-info}/LICENSE +0 -0
  388. {diffusers-0.32.1.dist-info → diffusers-0.33.0.dist-info}/entry_points.txt +0 -0
  389. {diffusers-0.32.1.dist-info → diffusers-0.33.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,924 @@
1
+ # Copyright 2024 The HunyuanVideo 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 inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import PIL.Image
20
+ import torch
21
+ from transformers import (
22
+ CLIPImageProcessor,
23
+ CLIPTextModel,
24
+ CLIPTokenizer,
25
+ LlamaTokenizerFast,
26
+ LlavaForConditionalGeneration,
27
+ )
28
+
29
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
30
+ from ...loaders import HunyuanVideoLoraLoaderMixin
31
+ from ...models import AutoencoderKLHunyuanVideo, HunyuanVideoTransformer3DModel
32
+ from ...schedulers import FlowMatchEulerDiscreteScheduler
33
+ from ...utils import is_torch_xla_available, logging, replace_example_docstring
34
+ from ...utils.torch_utils import randn_tensor
35
+ from ...video_processor import VideoProcessor
36
+ from ..pipeline_utils import DiffusionPipeline
37
+ from .pipeline_output import HunyuanVideoPipelineOutput
38
+
39
+
40
+ if is_torch_xla_available():
41
+ import torch_xla.core.xla_model as xm
42
+
43
+ XLA_AVAILABLE = True
44
+ else:
45
+ XLA_AVAILABLE = False
46
+
47
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
48
+
49
+
50
+ EXAMPLE_DOC_STRING = """
51
+ Examples:
52
+ ```python
53
+ >>> import torch
54
+ >>> from diffusers import HunyuanVideoImageToVideoPipeline, HunyuanVideoTransformer3DModel
55
+ >>> from diffusers.utils import load_image, export_to_video
56
+
57
+ >>> # Available checkpoints: hunyuanvideo-community/HunyuanVideo-I2V, hunyuanvideo-community/HunyuanVideo-I2V-33ch
58
+ >>> model_id = "hunyuanvideo-community/HunyuanVideo-I2V"
59
+ >>> transformer = HunyuanVideoTransformer3DModel.from_pretrained(
60
+ ... model_id, subfolder="transformer", torch_dtype=torch.bfloat16
61
+ ... )
62
+ >>> pipe = HunyuanVideoImageToVideoPipeline.from_pretrained(
63
+ ... model_id, transformer=transformer, torch_dtype=torch.float16
64
+ ... )
65
+ >>> pipe.vae.enable_tiling()
66
+ >>> pipe.to("cuda")
67
+
68
+ >>> prompt = "A man with short gray hair plays a red electric guitar."
69
+ >>> image = load_image(
70
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/guitar-man.png"
71
+ ... )
72
+
73
+ >>> # If using hunyuanvideo-community/HunyuanVideo-I2V
74
+ >>> output = pipe(image=image, prompt=prompt, guidance_scale=6.0).frames[0]
75
+
76
+ >>> # If using hunyuanvideo-community/HunyuanVideo-I2V-33ch
77
+ >>> output = pipe(image=image, prompt=prompt, guidance_scale=1.0, true_cfg_scale=1.0).frames[0]
78
+
79
+ >>> export_to_video(output, "output.mp4", fps=15)
80
+ ```
81
+ """
82
+
83
+
84
+ DEFAULT_PROMPT_TEMPLATE = {
85
+ "template": (
86
+ "<|start_header_id|>system<|end_header_id|>\n\n<image>\nDescribe the video by detailing the following aspects according to the reference image: "
87
+ "1. The main content and theme of the video."
88
+ "2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects."
89
+ "3. Actions, events, behaviors temporal relationships, physical movement changes of the objects."
90
+ "4. background environment, light, style and atmosphere."
91
+ "5. camera angles, movements, and transitions used in the video:<|eot_id|>\n\n"
92
+ "<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>"
93
+ "<|start_header_id|>assistant<|end_header_id|>\n\n"
94
+ ),
95
+ "crop_start": 103,
96
+ "image_emb_start": 5,
97
+ "image_emb_end": 581,
98
+ "image_emb_len": 576,
99
+ "double_return_token_id": 271,
100
+ }
101
+
102
+
103
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
104
+ def retrieve_timesteps(
105
+ scheduler,
106
+ num_inference_steps: Optional[int] = None,
107
+ device: Optional[Union[str, torch.device]] = None,
108
+ timesteps: Optional[List[int]] = None,
109
+ sigmas: Optional[List[float]] = None,
110
+ **kwargs,
111
+ ):
112
+ r"""
113
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
114
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
115
+
116
+ Args:
117
+ scheduler (`SchedulerMixin`):
118
+ The scheduler to get timesteps from.
119
+ num_inference_steps (`int`):
120
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
121
+ must be `None`.
122
+ device (`str` or `torch.device`, *optional*):
123
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
124
+ timesteps (`List[int]`, *optional*):
125
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
126
+ `num_inference_steps` and `sigmas` must be `None`.
127
+ sigmas (`List[float]`, *optional*):
128
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
129
+ `num_inference_steps` and `timesteps` must be `None`.
130
+
131
+ Returns:
132
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
133
+ second element is the number of inference steps.
134
+ """
135
+ if timesteps is not None and sigmas is not None:
136
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
137
+ if timesteps is not None:
138
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
139
+ if not accepts_timesteps:
140
+ raise ValueError(
141
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
142
+ f" timestep schedules. Please check whether you are using the correct scheduler."
143
+ )
144
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
145
+ timesteps = scheduler.timesteps
146
+ num_inference_steps = len(timesteps)
147
+ elif sigmas is not None:
148
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
149
+ if not accept_sigmas:
150
+ raise ValueError(
151
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
152
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
153
+ )
154
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
155
+ timesteps = scheduler.timesteps
156
+ num_inference_steps = len(timesteps)
157
+ else:
158
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
159
+ timesteps = scheduler.timesteps
160
+ return timesteps, num_inference_steps
161
+
162
+
163
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
164
+ def retrieve_latents(
165
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
166
+ ):
167
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
168
+ return encoder_output.latent_dist.sample(generator)
169
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
170
+ return encoder_output.latent_dist.mode()
171
+ elif hasattr(encoder_output, "latents"):
172
+ return encoder_output.latents
173
+ else:
174
+ raise AttributeError("Could not access latents of provided encoder_output")
175
+
176
+
177
+ class HunyuanVideoImageToVideoPipeline(DiffusionPipeline, HunyuanVideoLoraLoaderMixin):
178
+ r"""
179
+ Pipeline for image-to-video generation using HunyuanVideo.
180
+
181
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
182
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
183
+
184
+ Args:
185
+ text_encoder ([`LlavaForConditionalGeneration`]):
186
+ [Llava Llama3-8B](https://huggingface.co/xtuner/llava-llama-3-8b-v1_1-transformers).
187
+ tokenizer (`LlamaTokenizer`):
188
+ Tokenizer from [Llava Llama3-8B](https://huggingface.co/xtuner/llava-llama-3-8b-v1_1-transformers).
189
+ transformer ([`HunyuanVideoTransformer3DModel`]):
190
+ Conditional Transformer to denoise the encoded image latents.
191
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
192
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
193
+ vae ([`AutoencoderKLHunyuanVideo`]):
194
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
195
+ text_encoder_2 ([`CLIPTextModel`]):
196
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
197
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
198
+ tokenizer_2 (`CLIPTokenizer`):
199
+ Tokenizer of class
200
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
201
+ """
202
+
203
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
204
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
205
+
206
+ def __init__(
207
+ self,
208
+ text_encoder: LlavaForConditionalGeneration,
209
+ tokenizer: LlamaTokenizerFast,
210
+ transformer: HunyuanVideoTransformer3DModel,
211
+ vae: AutoencoderKLHunyuanVideo,
212
+ scheduler: FlowMatchEulerDiscreteScheduler,
213
+ text_encoder_2: CLIPTextModel,
214
+ tokenizer_2: CLIPTokenizer,
215
+ image_processor: CLIPImageProcessor,
216
+ ):
217
+ super().__init__()
218
+
219
+ self.register_modules(
220
+ vae=vae,
221
+ text_encoder=text_encoder,
222
+ tokenizer=tokenizer,
223
+ transformer=transformer,
224
+ scheduler=scheduler,
225
+ text_encoder_2=text_encoder_2,
226
+ tokenizer_2=tokenizer_2,
227
+ image_processor=image_processor,
228
+ )
229
+
230
+ self.vae_scaling_factor = self.vae.config.scaling_factor if getattr(self, "vae", None) else 0.476986
231
+ self.vae_scale_factor_temporal = self.vae.temporal_compression_ratio if getattr(self, "vae", None) else 4
232
+ self.vae_scale_factor_spatial = self.vae.spatial_compression_ratio if getattr(self, "vae", None) else 8
233
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
234
+
235
+ def _get_llama_prompt_embeds(
236
+ self,
237
+ image: torch.Tensor,
238
+ prompt: Union[str, List[str]],
239
+ prompt_template: Dict[str, Any],
240
+ num_videos_per_prompt: int = 1,
241
+ device: Optional[torch.device] = None,
242
+ dtype: Optional[torch.dtype] = None,
243
+ max_sequence_length: int = 256,
244
+ num_hidden_layers_to_skip: int = 2,
245
+ image_embed_interleave: int = 2,
246
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
247
+ device = device or self._execution_device
248
+ dtype = dtype or self.text_encoder.dtype
249
+
250
+ prompt = [prompt] if isinstance(prompt, str) else prompt
251
+ prompt = [prompt_template["template"].format(p) for p in prompt]
252
+
253
+ crop_start = prompt_template.get("crop_start", None)
254
+ if crop_start is None:
255
+ prompt_template_input = self.tokenizer(
256
+ prompt_template["template"],
257
+ padding="max_length",
258
+ return_tensors="pt",
259
+ return_length=False,
260
+ return_overflowing_tokens=False,
261
+ return_attention_mask=False,
262
+ )
263
+ crop_start = prompt_template_input["input_ids"].shape[-1]
264
+ # Remove <|start_header_id|>, <|end_header_id|>, assistant, <|eot_id|>, and placeholder {}
265
+ crop_start -= 5
266
+
267
+ max_sequence_length += crop_start
268
+ text_inputs = self.tokenizer(
269
+ prompt,
270
+ max_length=max_sequence_length,
271
+ padding="max_length",
272
+ truncation=True,
273
+ return_tensors="pt",
274
+ return_length=False,
275
+ return_overflowing_tokens=False,
276
+ return_attention_mask=True,
277
+ )
278
+ text_input_ids = text_inputs.input_ids.to(device=device)
279
+ prompt_attention_mask = text_inputs.attention_mask.to(device=device)
280
+
281
+ image_embeds = self.image_processor(image, return_tensors="pt").pixel_values.to(device)
282
+
283
+ prompt_embeds = self.text_encoder(
284
+ input_ids=text_input_ids,
285
+ attention_mask=prompt_attention_mask,
286
+ pixel_values=image_embeds,
287
+ output_hidden_states=True,
288
+ ).hidden_states[-(num_hidden_layers_to_skip + 1)]
289
+ prompt_embeds = prompt_embeds.to(dtype=dtype)
290
+
291
+ image_emb_len = prompt_template.get("image_emb_len", 576)
292
+ image_emb_start = prompt_template.get("image_emb_start", 5)
293
+ image_emb_end = prompt_template.get("image_emb_end", 581)
294
+ double_return_token_id = prompt_template.get("double_return_token_id", 271)
295
+
296
+ if crop_start is not None and crop_start > 0:
297
+ text_crop_start = crop_start - 1 + image_emb_len
298
+ batch_indices, last_double_return_token_indices = torch.where(text_input_ids == double_return_token_id)
299
+
300
+ if last_double_return_token_indices.shape[0] == 3:
301
+ # in case the prompt is too long
302
+ last_double_return_token_indices = torch.cat(
303
+ (last_double_return_token_indices, torch.tensor([text_input_ids.shape[-1]]))
304
+ )
305
+ batch_indices = torch.cat((batch_indices, torch.tensor([0])))
306
+
307
+ last_double_return_token_indices = last_double_return_token_indices.reshape(text_input_ids.shape[0], -1)[
308
+ :, -1
309
+ ]
310
+ batch_indices = batch_indices.reshape(text_input_ids.shape[0], -1)[:, -1]
311
+ assistant_crop_start = last_double_return_token_indices - 1 + image_emb_len - 4
312
+ assistant_crop_end = last_double_return_token_indices - 1 + image_emb_len
313
+ attention_mask_assistant_crop_start = last_double_return_token_indices - 4
314
+ attention_mask_assistant_crop_end = last_double_return_token_indices
315
+
316
+ prompt_embed_list = []
317
+ prompt_attention_mask_list = []
318
+ image_embed_list = []
319
+ image_attention_mask_list = []
320
+
321
+ for i in range(text_input_ids.shape[0]):
322
+ prompt_embed_list.append(
323
+ torch.cat(
324
+ [
325
+ prompt_embeds[i, text_crop_start : assistant_crop_start[i].item()],
326
+ prompt_embeds[i, assistant_crop_end[i].item() :],
327
+ ]
328
+ )
329
+ )
330
+ prompt_attention_mask_list.append(
331
+ torch.cat(
332
+ [
333
+ prompt_attention_mask[i, crop_start : attention_mask_assistant_crop_start[i].item()],
334
+ prompt_attention_mask[i, attention_mask_assistant_crop_end[i].item() :],
335
+ ]
336
+ )
337
+ )
338
+ image_embed_list.append(prompt_embeds[i, image_emb_start:image_emb_end])
339
+ image_attention_mask_list.append(
340
+ torch.ones(image_embed_list[-1].shape[0]).to(prompt_embeds.device).to(prompt_attention_mask.dtype)
341
+ )
342
+
343
+ prompt_embed_list = torch.stack(prompt_embed_list)
344
+ prompt_attention_mask_list = torch.stack(prompt_attention_mask_list)
345
+ image_embed_list = torch.stack(image_embed_list)
346
+ image_attention_mask_list = torch.stack(image_attention_mask_list)
347
+
348
+ if 0 < image_embed_interleave < 6:
349
+ image_embed_list = image_embed_list[:, ::image_embed_interleave, :]
350
+ image_attention_mask_list = image_attention_mask_list[:, ::image_embed_interleave]
351
+
352
+ assert (
353
+ prompt_embed_list.shape[0] == prompt_attention_mask_list.shape[0]
354
+ and image_embed_list.shape[0] == image_attention_mask_list.shape[0]
355
+ )
356
+
357
+ prompt_embeds = torch.cat([image_embed_list, prompt_embed_list], dim=1)
358
+ prompt_attention_mask = torch.cat([image_attention_mask_list, prompt_attention_mask_list], dim=1)
359
+
360
+ return prompt_embeds, prompt_attention_mask
361
+
362
+ def _get_clip_prompt_embeds(
363
+ self,
364
+ prompt: Union[str, List[str]],
365
+ num_videos_per_prompt: int = 1,
366
+ device: Optional[torch.device] = None,
367
+ dtype: Optional[torch.dtype] = None,
368
+ max_sequence_length: int = 77,
369
+ ) -> torch.Tensor:
370
+ device = device or self._execution_device
371
+ dtype = dtype or self.text_encoder_2.dtype
372
+
373
+ prompt = [prompt] if isinstance(prompt, str) else prompt
374
+
375
+ text_inputs = self.tokenizer_2(
376
+ prompt,
377
+ padding="max_length",
378
+ max_length=max_sequence_length,
379
+ truncation=True,
380
+ return_tensors="pt",
381
+ )
382
+
383
+ text_input_ids = text_inputs.input_ids
384
+ untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
385
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
386
+ removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
387
+ logger.warning(
388
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
389
+ f" {max_sequence_length} tokens: {removed_text}"
390
+ )
391
+
392
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False).pooler_output
393
+ return prompt_embeds
394
+
395
+ def encode_prompt(
396
+ self,
397
+ image: torch.Tensor,
398
+ prompt: Union[str, List[str]],
399
+ prompt_2: Union[str, List[str]] = None,
400
+ prompt_template: Dict[str, Any] = DEFAULT_PROMPT_TEMPLATE,
401
+ num_videos_per_prompt: int = 1,
402
+ prompt_embeds: Optional[torch.Tensor] = None,
403
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
404
+ prompt_attention_mask: Optional[torch.Tensor] = None,
405
+ device: Optional[torch.device] = None,
406
+ dtype: Optional[torch.dtype] = None,
407
+ max_sequence_length: int = 256,
408
+ image_embed_interleave: int = 2,
409
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
410
+ if prompt_embeds is None:
411
+ prompt_embeds, prompt_attention_mask = self._get_llama_prompt_embeds(
412
+ image,
413
+ prompt,
414
+ prompt_template,
415
+ num_videos_per_prompt,
416
+ device=device,
417
+ dtype=dtype,
418
+ max_sequence_length=max_sequence_length,
419
+ image_embed_interleave=image_embed_interleave,
420
+ )
421
+
422
+ if pooled_prompt_embeds is None:
423
+ if prompt_2 is None:
424
+ prompt_2 = prompt
425
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
426
+ prompt,
427
+ num_videos_per_prompt,
428
+ device=device,
429
+ dtype=dtype,
430
+ max_sequence_length=77,
431
+ )
432
+
433
+ return prompt_embeds, pooled_prompt_embeds, prompt_attention_mask
434
+
435
+ def check_inputs(
436
+ self,
437
+ prompt,
438
+ prompt_2,
439
+ height,
440
+ width,
441
+ prompt_embeds=None,
442
+ callback_on_step_end_tensor_inputs=None,
443
+ prompt_template=None,
444
+ true_cfg_scale=1.0,
445
+ guidance_scale=1.0,
446
+ ):
447
+ if height % 16 != 0 or width % 16 != 0:
448
+ raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
449
+
450
+ if callback_on_step_end_tensor_inputs is not None and not all(
451
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
452
+ ):
453
+ raise ValueError(
454
+ 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]}"
455
+ )
456
+
457
+ if prompt is not None and prompt_embeds is not None:
458
+ raise ValueError(
459
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
460
+ " only forward one of the two."
461
+ )
462
+ elif prompt_2 is not None and prompt_embeds is not None:
463
+ raise ValueError(
464
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
465
+ " only forward one of the two."
466
+ )
467
+ elif prompt is None and prompt_embeds is None:
468
+ raise ValueError(
469
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
470
+ )
471
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
472
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
473
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
474
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
475
+
476
+ if prompt_template is not None:
477
+ if not isinstance(prompt_template, dict):
478
+ raise ValueError(f"`prompt_template` has to be of type `dict` but is {type(prompt_template)}")
479
+ if "template" not in prompt_template:
480
+ raise ValueError(
481
+ f"`prompt_template` has to contain a key `template` but only found {prompt_template.keys()}"
482
+ )
483
+
484
+ if true_cfg_scale > 1.0 and guidance_scale > 1.0:
485
+ logger.warning(
486
+ "Both `true_cfg_scale` and `guidance_scale` are greater than 1.0. This will result in both "
487
+ "classifier-free guidance and embedded-guidance to be applied. This is not recommended "
488
+ "as it may lead to higher memory usage, slower inference and potentially worse results."
489
+ )
490
+
491
+ def prepare_latents(
492
+ self,
493
+ image: torch.Tensor,
494
+ batch_size: int,
495
+ num_channels_latents: int = 32,
496
+ height: int = 720,
497
+ width: int = 1280,
498
+ num_frames: int = 129,
499
+ dtype: Optional[torch.dtype] = None,
500
+ device: Optional[torch.device] = None,
501
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
502
+ latents: Optional[torch.Tensor] = None,
503
+ image_condition_type: str = "latent_concat",
504
+ ) -> torch.Tensor:
505
+ if isinstance(generator, list) and len(generator) != batch_size:
506
+ raise ValueError(
507
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
508
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
509
+ )
510
+
511
+ num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
512
+ latent_height, latent_width = height // self.vae_scale_factor_spatial, width // self.vae_scale_factor_spatial
513
+ shape = (batch_size, num_channels_latents, num_latent_frames, latent_height, latent_width)
514
+
515
+ image = image.unsqueeze(2) # [B, C, 1, H, W]
516
+ if isinstance(generator, list):
517
+ image_latents = [
518
+ retrieve_latents(self.vae.encode(image[i].unsqueeze(0)), generator[i], "argmax")
519
+ for i in range(batch_size)
520
+ ]
521
+ else:
522
+ image_latents = [retrieve_latents(self.vae.encode(img.unsqueeze(0)), generator, "argmax") for img in image]
523
+
524
+ image_latents = torch.cat(image_latents, dim=0).to(dtype) * self.vae_scaling_factor
525
+ image_latents = image_latents.repeat(1, 1, num_latent_frames, 1, 1)
526
+
527
+ if latents is None:
528
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
529
+ else:
530
+ latents = latents.to(device=device, dtype=dtype)
531
+
532
+ t = torch.tensor([0.999]).to(device=device)
533
+ latents = latents * t + image_latents * (1 - t)
534
+
535
+ if image_condition_type == "token_replace":
536
+ image_latents = image_latents[:, :, :1]
537
+
538
+ return latents, image_latents
539
+
540
+ def enable_vae_slicing(self):
541
+ r"""
542
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
543
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
544
+ """
545
+ self.vae.enable_slicing()
546
+
547
+ def disable_vae_slicing(self):
548
+ r"""
549
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
550
+ computing decoding in one step.
551
+ """
552
+ self.vae.disable_slicing()
553
+
554
+ def enable_vae_tiling(self):
555
+ r"""
556
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
557
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
558
+ processing larger images.
559
+ """
560
+ self.vae.enable_tiling()
561
+
562
+ def disable_vae_tiling(self):
563
+ r"""
564
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
565
+ computing decoding in one step.
566
+ """
567
+ self.vae.disable_tiling()
568
+
569
+ @property
570
+ def guidance_scale(self):
571
+ return self._guidance_scale
572
+
573
+ @property
574
+ def num_timesteps(self):
575
+ return self._num_timesteps
576
+
577
+ @property
578
+ def attention_kwargs(self):
579
+ return self._attention_kwargs
580
+
581
+ @property
582
+ def current_timestep(self):
583
+ return self._current_timestep
584
+
585
+ @property
586
+ def interrupt(self):
587
+ return self._interrupt
588
+
589
+ @torch.no_grad()
590
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
591
+ def __call__(
592
+ self,
593
+ image: PIL.Image.Image,
594
+ prompt: Union[str, List[str]] = None,
595
+ prompt_2: Union[str, List[str]] = None,
596
+ negative_prompt: Union[str, List[str]] = None,
597
+ negative_prompt_2: Union[str, List[str]] = None,
598
+ height: int = 720,
599
+ width: int = 1280,
600
+ num_frames: int = 129,
601
+ num_inference_steps: int = 50,
602
+ sigmas: List[float] = None,
603
+ true_cfg_scale: float = 1.0,
604
+ guidance_scale: float = 1.0,
605
+ num_videos_per_prompt: Optional[int] = 1,
606
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
607
+ latents: Optional[torch.Tensor] = None,
608
+ prompt_embeds: Optional[torch.Tensor] = None,
609
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
610
+ prompt_attention_mask: Optional[torch.Tensor] = None,
611
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
612
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
613
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
614
+ output_type: Optional[str] = "pil",
615
+ return_dict: bool = True,
616
+ attention_kwargs: Optional[Dict[str, Any]] = None,
617
+ callback_on_step_end: Optional[
618
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
619
+ ] = None,
620
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
621
+ prompt_template: Dict[str, Any] = DEFAULT_PROMPT_TEMPLATE,
622
+ max_sequence_length: int = 256,
623
+ image_embed_interleave: Optional[int] = None,
624
+ ):
625
+ r"""
626
+ The call function to the pipeline for generation.
627
+
628
+ Args:
629
+ prompt (`str` or `List[str]`, *optional*):
630
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
631
+ instead.
632
+ prompt_2 (`str` or `List[str]`, *optional*):
633
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
634
+ will be used instead.
635
+ negative_prompt (`str` or `List[str]`, *optional*):
636
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
637
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `true_cfg_scale` is
638
+ not greater than `1`).
639
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
640
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
641
+ `text_encoder_2`. If not defined, `negative_prompt` is used in all the text-encoders.
642
+ height (`int`, defaults to `720`):
643
+ The height in pixels of the generated image.
644
+ width (`int`, defaults to `1280`):
645
+ The width in pixels of the generated image.
646
+ num_frames (`int`, defaults to `129`):
647
+ The number of frames in the generated video.
648
+ num_inference_steps (`int`, defaults to `50`):
649
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
650
+ expense of slower inference.
651
+ sigmas (`List[float]`, *optional*):
652
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
653
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
654
+ will be used.
655
+ true_cfg_scale (`float`, *optional*, defaults to 1.0):
656
+ When > 1.0 and a provided `negative_prompt`, enables true classifier-free guidance.
657
+ guidance_scale (`float`, defaults to `1.0`):
658
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
659
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
660
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
661
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
662
+ usually at the expense of lower image quality. Note that the only available HunyuanVideo model is
663
+ CFG-distilled, which means that traditional guidance between unconditional and conditional latent is
664
+ not applied.
665
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
666
+ The number of images to generate per prompt.
667
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
668
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
669
+ generation deterministic.
670
+ latents (`torch.Tensor`, *optional*):
671
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
672
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
673
+ tensor is generated by sampling using the supplied random `generator`.
674
+ prompt_embeds (`torch.Tensor`, *optional*):
675
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
676
+ provided, text embeddings are generated from the `prompt` input argument.
677
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
678
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
679
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
680
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
681
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
682
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
683
+ argument.
684
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
685
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
686
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
687
+ input argument.
688
+ output_type (`str`, *optional*, defaults to `"pil"`):
689
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
690
+ return_dict (`bool`, *optional*, defaults to `True`):
691
+ Whether or not to return a [`HunyuanVideoPipelineOutput`] instead of a plain tuple.
692
+ attention_kwargs (`dict`, *optional*):
693
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
694
+ `self.processor` in
695
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
696
+ clip_skip (`int`, *optional*):
697
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
698
+ the output of the pre-final layer will be used for computing the prompt embeddings.
699
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
700
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
701
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
702
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
703
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
704
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
705
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
706
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
707
+ `._callback_tensor_inputs` attribute of your pipeline class.
708
+
709
+ Examples:
710
+
711
+ Returns:
712
+ [`~HunyuanVideoPipelineOutput`] or `tuple`:
713
+ If `return_dict` is `True`, [`HunyuanVideoPipelineOutput`] is returned, otherwise a `tuple` is returned
714
+ where the first element is a list with the generated images and the second element is a list of `bool`s
715
+ indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
716
+ """
717
+
718
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
719
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
720
+
721
+ # 1. Check inputs. Raise error if not correct
722
+ self.check_inputs(
723
+ prompt,
724
+ prompt_2,
725
+ height,
726
+ width,
727
+ prompt_embeds,
728
+ callback_on_step_end_tensor_inputs,
729
+ prompt_template,
730
+ true_cfg_scale,
731
+ guidance_scale,
732
+ )
733
+
734
+ image_condition_type = self.transformer.config.image_condition_type
735
+ has_neg_prompt = negative_prompt is not None or (
736
+ negative_prompt_embeds is not None and negative_pooled_prompt_embeds is not None
737
+ )
738
+ do_true_cfg = true_cfg_scale > 1 and has_neg_prompt
739
+ image_embed_interleave = (
740
+ image_embed_interleave
741
+ if image_embed_interleave is not None
742
+ else (
743
+ 2 if image_condition_type == "latent_concat" else 4 if image_condition_type == "token_replace" else 1
744
+ )
745
+ )
746
+
747
+ self._guidance_scale = guidance_scale
748
+ self._attention_kwargs = attention_kwargs
749
+ self._current_timestep = None
750
+ self._interrupt = False
751
+
752
+ device = self._execution_device
753
+
754
+ # 2. Define call parameters
755
+ if prompt is not None and isinstance(prompt, str):
756
+ batch_size = 1
757
+ elif prompt is not None and isinstance(prompt, list):
758
+ batch_size = len(prompt)
759
+ else:
760
+ batch_size = prompt_embeds.shape[0]
761
+
762
+ # 3. Prepare latent variables
763
+ vae_dtype = self.vae.dtype
764
+ image_tensor = self.video_processor.preprocess(image, height, width).to(device, vae_dtype)
765
+
766
+ if image_condition_type == "latent_concat":
767
+ num_channels_latents = (self.transformer.config.in_channels - 1) // 2
768
+ elif image_condition_type == "token_replace":
769
+ num_channels_latents = self.transformer.config.in_channels
770
+
771
+ latents, image_latents = self.prepare_latents(
772
+ image_tensor,
773
+ batch_size * num_videos_per_prompt,
774
+ num_channels_latents,
775
+ height,
776
+ width,
777
+ num_frames,
778
+ torch.float32,
779
+ device,
780
+ generator,
781
+ latents,
782
+ image_condition_type,
783
+ )
784
+ if image_condition_type == "latent_concat":
785
+ image_latents[:, :, 1:] = 0
786
+ mask = image_latents.new_ones(image_latents.shape[0], 1, *image_latents.shape[2:])
787
+ mask[:, :, 1:] = 0
788
+
789
+ # 4. Encode input prompt
790
+ transformer_dtype = self.transformer.dtype
791
+ prompt_embeds, pooled_prompt_embeds, prompt_attention_mask = self.encode_prompt(
792
+ image=image,
793
+ prompt=prompt,
794
+ prompt_2=prompt_2,
795
+ prompt_template=prompt_template,
796
+ num_videos_per_prompt=num_videos_per_prompt,
797
+ prompt_embeds=prompt_embeds,
798
+ pooled_prompt_embeds=pooled_prompt_embeds,
799
+ prompt_attention_mask=prompt_attention_mask,
800
+ device=device,
801
+ max_sequence_length=max_sequence_length,
802
+ image_embed_interleave=image_embed_interleave,
803
+ )
804
+ prompt_embeds = prompt_embeds.to(transformer_dtype)
805
+ prompt_attention_mask = prompt_attention_mask.to(transformer_dtype)
806
+ pooled_prompt_embeds = pooled_prompt_embeds.to(transformer_dtype)
807
+
808
+ if do_true_cfg:
809
+ black_image = PIL.Image.new("RGB", (width, height), 0)
810
+ negative_prompt_embeds, negative_pooled_prompt_embeds, negative_prompt_attention_mask = self.encode_prompt(
811
+ image=black_image,
812
+ prompt=negative_prompt,
813
+ prompt_2=negative_prompt_2,
814
+ prompt_template=prompt_template,
815
+ num_videos_per_prompt=num_videos_per_prompt,
816
+ prompt_embeds=negative_prompt_embeds,
817
+ pooled_prompt_embeds=negative_pooled_prompt_embeds,
818
+ prompt_attention_mask=negative_prompt_attention_mask,
819
+ device=device,
820
+ max_sequence_length=max_sequence_length,
821
+ )
822
+ negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
823
+ negative_prompt_attention_mask = negative_prompt_attention_mask.to(transformer_dtype)
824
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.to(transformer_dtype)
825
+
826
+ # 5. Prepare timesteps
827
+ sigmas = np.linspace(1.0, 0.0, num_inference_steps + 1)[:-1] if sigmas is None else sigmas
828
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, sigmas=sigmas)
829
+
830
+ # 6. Prepare guidance condition
831
+ guidance = None
832
+ if self.transformer.config.guidance_embeds:
833
+ guidance = (
834
+ torch.tensor([guidance_scale] * latents.shape[0], dtype=transformer_dtype, device=device) * 1000.0
835
+ )
836
+
837
+ # 7. Denoising loop
838
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
839
+ self._num_timesteps = len(timesteps)
840
+
841
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
842
+ for i, t in enumerate(timesteps):
843
+ if self.interrupt:
844
+ continue
845
+
846
+ self._current_timestep = t
847
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
848
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
849
+
850
+ if image_condition_type == "latent_concat":
851
+ latent_model_input = torch.cat([latents, image_latents, mask], dim=1).to(transformer_dtype)
852
+ elif image_condition_type == "token_replace":
853
+ latent_model_input = torch.cat([image_latents, latents[:, :, 1:]], dim=2).to(transformer_dtype)
854
+
855
+ noise_pred = self.transformer(
856
+ hidden_states=latent_model_input,
857
+ timestep=timestep,
858
+ encoder_hidden_states=prompt_embeds,
859
+ encoder_attention_mask=prompt_attention_mask,
860
+ pooled_projections=pooled_prompt_embeds,
861
+ guidance=guidance,
862
+ attention_kwargs=attention_kwargs,
863
+ return_dict=False,
864
+ )[0]
865
+
866
+ if do_true_cfg:
867
+ neg_noise_pred = self.transformer(
868
+ hidden_states=latent_model_input,
869
+ timestep=timestep,
870
+ encoder_hidden_states=negative_prompt_embeds,
871
+ encoder_attention_mask=negative_prompt_attention_mask,
872
+ pooled_projections=negative_pooled_prompt_embeds,
873
+ guidance=guidance,
874
+ attention_kwargs=attention_kwargs,
875
+ return_dict=False,
876
+ )[0]
877
+ noise_pred = neg_noise_pred + true_cfg_scale * (noise_pred - neg_noise_pred)
878
+
879
+ # compute the previous noisy sample x_t -> x_t-1
880
+ if image_condition_type == "latent_concat":
881
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
882
+ elif image_condition_type == "token_replace":
883
+ latents = latents = self.scheduler.step(
884
+ noise_pred[:, :, 1:], t, latents[:, :, 1:], return_dict=False
885
+ )[0]
886
+ latents = torch.cat([image_latents, latents], dim=2)
887
+
888
+ if callback_on_step_end is not None:
889
+ callback_kwargs = {}
890
+ for k in callback_on_step_end_tensor_inputs:
891
+ callback_kwargs[k] = locals()[k]
892
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
893
+
894
+ latents = callback_outputs.pop("latents", latents)
895
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
896
+
897
+ # call the callback, if provided
898
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
899
+ progress_bar.update()
900
+
901
+ if XLA_AVAILABLE:
902
+ xm.mark_step()
903
+
904
+ self._current_timestep = None
905
+
906
+ if not output_type == "latent":
907
+ latents = latents.to(self.vae.dtype) / self.vae_scaling_factor
908
+ video = self.vae.decode(latents, return_dict=False)[0]
909
+ if image_condition_type == "latent_concat":
910
+ video = video[:, :, 4:, :, :]
911
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
912
+ else:
913
+ if image_condition_type == "latent_concat":
914
+ video = latents[:, :, 1:, :, :]
915
+ else:
916
+ video = latents
917
+
918
+ # Offload all models
919
+ self.maybe_free_model_hooks()
920
+
921
+ if not return_dict:
922
+ return (video,)
923
+
924
+ return HunyuanVideoPipelineOutput(frames=video)