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,792 @@
1
+ # Copyright 2025 The NVIDIA 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 Callable, Dict, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ from transformers import T5EncoderModel, T5TokenizerFast
21
+
22
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
23
+ from ...image_processor import PipelineImageInput
24
+ from ...models import AutoencoderKLWan, CosmosTransformer3DModel
25
+ from ...schedulers import FlowMatchEulerDiscreteScheduler
26
+ from ...utils import is_cosmos_guardrail_available, is_torch_xla_available, logging, replace_example_docstring
27
+ from ...utils.torch_utils import randn_tensor
28
+ from ...video_processor import VideoProcessor
29
+ from ..pipeline_utils import DiffusionPipeline
30
+ from .pipeline_output import CosmosPipelineOutput
31
+
32
+
33
+ if is_cosmos_guardrail_available():
34
+ from cosmos_guardrail import CosmosSafetyChecker
35
+ else:
36
+
37
+ class CosmosSafetyChecker:
38
+ def __init__(self, *args, **kwargs):
39
+ raise ImportError(
40
+ "`cosmos_guardrail` is not installed. Please install it to use the safety checker for Cosmos: `pip install cosmos_guardrail`."
41
+ )
42
+
43
+
44
+ if is_torch_xla_available():
45
+ import torch_xla.core.xla_model as xm
46
+
47
+ XLA_AVAILABLE = True
48
+ else:
49
+ XLA_AVAILABLE = False
50
+
51
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
52
+
53
+
54
+ EXAMPLE_DOC_STRING = """
55
+ Examples:
56
+ ```python
57
+ >>> import torch
58
+ >>> from diffusers import Cosmos2VideoToWorldPipeline
59
+ >>> from diffusers.utils import export_to_video, load_image
60
+
61
+ >>> # Available checkpoints: nvidia/Cosmos-Predict2-2B-Video2World, nvidia/Cosmos-Predict2-14B-Video2World
62
+ >>> model_id = "nvidia/Cosmos-Predict2-2B-Video2World"
63
+ >>> pipe = Cosmos2VideoToWorldPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
64
+ >>> pipe.to("cuda")
65
+
66
+ >>> prompt = "A close-up shot captures a vibrant yellow scrubber vigorously working on a grimy plate, its bristles moving in circular motions to lift stubborn grease and food residue. The dish, once covered in remnants of a hearty meal, gradually reveals its original glossy surface. Suds form and bubble around the scrubber, creating a satisfying visual of cleanliness in progress. The sound of scrubbing fills the air, accompanied by the gentle clinking of the dish against the sink. As the scrubber continues its task, the dish transforms, gleaming under the bright kitchen lights, symbolizing the triumph of cleanliness over mess."
67
+ >>> negative_prompt = "The video captures a series of frames showing ugly scenes, static with no motion, motion blur, over-saturation, shaky footage, low resolution, grainy texture, pixelated images, poorly lit areas, underexposed and overexposed scenes, poor color balance, washed out colors, choppy sequences, jerky movements, low frame rate, artifacting, color banding, unnatural transitions, outdated special effects, fake elements, unconvincing visuals, poorly edited content, jump cuts, visual noise, and flickering. Overall, the video is of poor quality."
68
+ >>> image = load_image(
69
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/yellow-scrubber.png"
70
+ ... )
71
+
72
+ >>> video = pipe(
73
+ ... image=image, prompt=prompt, negative_prompt=negative_prompt, generator=torch.Generator().manual_seed(1)
74
+ ... ).frames[0]
75
+ >>> export_to_video(video, "output.mp4", fps=16)
76
+ ```
77
+ """
78
+
79
+
80
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
81
+ def retrieve_timesteps(
82
+ scheduler,
83
+ num_inference_steps: Optional[int] = None,
84
+ device: Optional[Union[str, torch.device]] = None,
85
+ timesteps: Optional[List[int]] = None,
86
+ sigmas: Optional[List[float]] = None,
87
+ **kwargs,
88
+ ):
89
+ r"""
90
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
91
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
92
+
93
+ Args:
94
+ scheduler (`SchedulerMixin`):
95
+ The scheduler to get timesteps from.
96
+ num_inference_steps (`int`):
97
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
98
+ must be `None`.
99
+ device (`str` or `torch.device`, *optional*):
100
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
101
+ timesteps (`List[int]`, *optional*):
102
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
103
+ `num_inference_steps` and `sigmas` must be `None`.
104
+ sigmas (`List[float]`, *optional*):
105
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
106
+ `num_inference_steps` and `timesteps` must be `None`.
107
+
108
+ Returns:
109
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
110
+ second element is the number of inference steps.
111
+ """
112
+ if timesteps is not None and sigmas is not None:
113
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
114
+ if timesteps is not None:
115
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
116
+ if not accepts_timesteps:
117
+ raise ValueError(
118
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
119
+ f" timestep schedules. Please check whether you are using the correct scheduler."
120
+ )
121
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
122
+ timesteps = scheduler.timesteps
123
+ num_inference_steps = len(timesteps)
124
+ elif sigmas is not None:
125
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
126
+ if not accept_sigmas:
127
+ raise ValueError(
128
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
129
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
130
+ )
131
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
132
+ timesteps = scheduler.timesteps
133
+ num_inference_steps = len(timesteps)
134
+ else:
135
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
136
+ timesteps = scheduler.timesteps
137
+ return timesteps, num_inference_steps
138
+
139
+
140
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
141
+ def retrieve_latents(
142
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
143
+ ):
144
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
145
+ return encoder_output.latent_dist.sample(generator)
146
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
147
+ return encoder_output.latent_dist.mode()
148
+ elif hasattr(encoder_output, "latents"):
149
+ return encoder_output.latents
150
+ else:
151
+ raise AttributeError("Could not access latents of provided encoder_output")
152
+
153
+
154
+ class Cosmos2VideoToWorldPipeline(DiffusionPipeline):
155
+ r"""
156
+ Pipeline for video-to-world generation using [Cosmos Predict2](https://github.com/nvidia-cosmos/cosmos-predict2).
157
+
158
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
159
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
160
+
161
+ Args:
162
+ text_encoder ([`T5EncoderModel`]):
163
+ Frozen text-encoder. Cosmos uses
164
+ [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel); specifically the
165
+ [t5-11b](https://huggingface.co/google-t5/t5-11b) variant.
166
+ tokenizer (`T5TokenizerFast`):
167
+ Tokenizer of class
168
+ [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
169
+ transformer ([`CosmosTransformer3DModel`]):
170
+ Conditional Transformer to denoise the encoded image latents.
171
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
172
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
173
+ vae ([`AutoencoderKLWan`]):
174
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
175
+ """
176
+
177
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
178
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
179
+ # We mark safety_checker as optional here to get around some test failures, but it is not really optional
180
+ _optional_components = ["safety_checker"]
181
+
182
+ def __init__(
183
+ self,
184
+ text_encoder: T5EncoderModel,
185
+ tokenizer: T5TokenizerFast,
186
+ transformer: CosmosTransformer3DModel,
187
+ vae: AutoencoderKLWan,
188
+ scheduler: FlowMatchEulerDiscreteScheduler,
189
+ safety_checker: CosmosSafetyChecker = None,
190
+ ):
191
+ super().__init__()
192
+
193
+ if safety_checker is None:
194
+ safety_checker = CosmosSafetyChecker()
195
+
196
+ self.register_modules(
197
+ vae=vae,
198
+ text_encoder=text_encoder,
199
+ tokenizer=tokenizer,
200
+ transformer=transformer,
201
+ scheduler=scheduler,
202
+ safety_checker=safety_checker,
203
+ )
204
+
205
+ self.vae_scale_factor_temporal = 2 ** sum(self.vae.temperal_downsample) if getattr(self, "vae", None) else 4
206
+ self.vae_scale_factor_spatial = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8
207
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
208
+
209
+ self.sigma_max = 80.0
210
+ self.sigma_min = 0.002
211
+ self.sigma_data = 1.0
212
+ self.final_sigmas_type = "sigma_min"
213
+ if self.scheduler is not None:
214
+ self.scheduler.register_to_config(
215
+ sigma_max=self.sigma_max,
216
+ sigma_min=self.sigma_min,
217
+ sigma_data=self.sigma_data,
218
+ final_sigmas_type=self.final_sigmas_type,
219
+ )
220
+
221
+ # Copied from diffusers.pipelines.cosmos.pipeline_cosmos_text2world.CosmosTextToWorldPipeline._get_t5_prompt_embeds
222
+ def _get_t5_prompt_embeds(
223
+ self,
224
+ prompt: Union[str, List[str]] = None,
225
+ max_sequence_length: int = 512,
226
+ device: Optional[torch.device] = None,
227
+ dtype: Optional[torch.dtype] = None,
228
+ ):
229
+ device = device or self._execution_device
230
+ dtype = dtype or self.text_encoder.dtype
231
+ prompt = [prompt] if isinstance(prompt, str) else prompt
232
+
233
+ text_inputs = self.tokenizer(
234
+ prompt,
235
+ padding="max_length",
236
+ max_length=max_sequence_length,
237
+ truncation=True,
238
+ return_tensors="pt",
239
+ return_length=True,
240
+ return_offsets_mapping=False,
241
+ )
242
+ text_input_ids = text_inputs.input_ids
243
+ prompt_attention_mask = text_inputs.attention_mask.bool().to(device)
244
+
245
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
246
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
247
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
248
+ logger.warning(
249
+ "The following part of your input was truncated because `max_sequence_length` is set to "
250
+ f" {max_sequence_length} tokens: {removed_text}"
251
+ )
252
+
253
+ prompt_embeds = self.text_encoder(
254
+ text_input_ids.to(device), attention_mask=prompt_attention_mask
255
+ ).last_hidden_state
256
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
257
+
258
+ lengths = prompt_attention_mask.sum(dim=1).cpu()
259
+ for i, length in enumerate(lengths):
260
+ prompt_embeds[i, length:] = 0
261
+
262
+ return prompt_embeds
263
+
264
+ # Copied from diffusers.pipelines.cosmos.pipeline_cosmos_text2world.CosmosTextToWorldPipeline.encode_prompt
265
+ def encode_prompt(
266
+ self,
267
+ prompt: Union[str, List[str]],
268
+ negative_prompt: Optional[Union[str, List[str]]] = None,
269
+ do_classifier_free_guidance: bool = True,
270
+ num_videos_per_prompt: int = 1,
271
+ prompt_embeds: Optional[torch.Tensor] = None,
272
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
273
+ max_sequence_length: int = 512,
274
+ device: Optional[torch.device] = None,
275
+ dtype: Optional[torch.dtype] = None,
276
+ ):
277
+ r"""
278
+ Encodes the prompt into text encoder hidden states.
279
+
280
+ Args:
281
+ prompt (`str` or `List[str]`, *optional*):
282
+ prompt to be encoded
283
+ negative_prompt (`str` or `List[str]`, *optional*):
284
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
285
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
286
+ less than `1`).
287
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
288
+ Whether to use classifier free guidance or not.
289
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
290
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
291
+ prompt_embeds (`torch.Tensor`, *optional*):
292
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
293
+ provided, text embeddings will be generated from `prompt` input argument.
294
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
295
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
296
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
297
+ argument.
298
+ device: (`torch.device`, *optional*):
299
+ torch device
300
+ dtype: (`torch.dtype`, *optional*):
301
+ torch dtype
302
+ """
303
+ device = device or self._execution_device
304
+
305
+ prompt = [prompt] if isinstance(prompt, str) else prompt
306
+ if prompt is not None:
307
+ batch_size = len(prompt)
308
+ else:
309
+ batch_size = prompt_embeds.shape[0]
310
+
311
+ if prompt_embeds is None:
312
+ prompt_embeds = self._get_t5_prompt_embeds(
313
+ prompt=prompt, max_sequence_length=max_sequence_length, device=device, dtype=dtype
314
+ )
315
+
316
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
317
+ _, seq_len, _ = prompt_embeds.shape
318
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
319
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
320
+
321
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
322
+ negative_prompt = negative_prompt or ""
323
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
324
+
325
+ if prompt is not None and type(prompt) is not type(negative_prompt):
326
+ raise TypeError(
327
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
328
+ f" {type(prompt)}."
329
+ )
330
+ elif batch_size != len(negative_prompt):
331
+ raise ValueError(
332
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
333
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
334
+ " the batch size of `prompt`."
335
+ )
336
+
337
+ negative_prompt_embeds = self._get_t5_prompt_embeds(
338
+ prompt=negative_prompt, max_sequence_length=max_sequence_length, device=device, dtype=dtype
339
+ )
340
+
341
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
342
+ _, seq_len, _ = negative_prompt_embeds.shape
343
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_videos_per_prompt, 1)
344
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
345
+
346
+ return prompt_embeds, negative_prompt_embeds
347
+
348
+ def prepare_latents(
349
+ self,
350
+ video: torch.Tensor,
351
+ batch_size: int,
352
+ num_channels_latents: 16,
353
+ height: int = 704,
354
+ width: int = 1280,
355
+ num_frames: int = 93,
356
+ do_classifier_free_guidance: bool = True,
357
+ dtype: Optional[torch.dtype] = None,
358
+ device: Optional[torch.device] = None,
359
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
360
+ latents: Optional[torch.Tensor] = None,
361
+ ) -> torch.Tensor:
362
+ if isinstance(generator, list) and len(generator) != batch_size:
363
+ raise ValueError(
364
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
365
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
366
+ )
367
+
368
+ num_cond_frames = video.size(2)
369
+ if num_cond_frames >= num_frames:
370
+ # Take the last `num_frames` frames for conditioning
371
+ num_cond_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
372
+ video = video[:, :, -num_frames:]
373
+ else:
374
+ num_cond_latent_frames = (num_cond_frames - 1) // self.vae_scale_factor_temporal + 1
375
+ num_padding_frames = num_frames - num_cond_frames
376
+ last_frame = video[:, :, -1:]
377
+ padding = last_frame.repeat(1, 1, num_padding_frames, 1, 1)
378
+ video = torch.cat([video, padding], dim=2)
379
+
380
+ if isinstance(generator, list):
381
+ init_latents = [
382
+ retrieve_latents(self.vae.encode(video[i].unsqueeze(0)), generator=generator[i])
383
+ for i in range(batch_size)
384
+ ]
385
+ else:
386
+ init_latents = [retrieve_latents(self.vae.encode(vid.unsqueeze(0)), generator) for vid in video]
387
+
388
+ init_latents = torch.cat(init_latents, dim=0).to(dtype)
389
+
390
+ latents_mean = (
391
+ torch.tensor(self.vae.config.latents_mean).view(1, self.vae.config.z_dim, 1, 1, 1).to(device, dtype)
392
+ )
393
+ latents_std = (
394
+ torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(device, dtype)
395
+ )
396
+ init_latents = (init_latents - latents_mean) / latents_std * self.scheduler.config.sigma_data
397
+
398
+ num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
399
+ latent_height = height // self.vae_scale_factor_spatial
400
+ latent_width = width // self.vae_scale_factor_spatial
401
+ shape = (batch_size, num_channels_latents, num_latent_frames, latent_height, latent_width)
402
+
403
+ if latents is None:
404
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
405
+ else:
406
+ latents = latents.to(device=device, dtype=dtype)
407
+
408
+ latents = latents * self.scheduler.config.sigma_max
409
+
410
+ padding_shape = (batch_size, 1, num_latent_frames, latent_height, latent_width)
411
+ ones_padding = latents.new_ones(padding_shape)
412
+ zeros_padding = latents.new_zeros(padding_shape)
413
+
414
+ cond_indicator = latents.new_zeros(1, 1, latents.size(2), 1, 1)
415
+ cond_indicator[:, :, :num_cond_latent_frames] = 1.0
416
+ cond_mask = cond_indicator * ones_padding + (1 - cond_indicator) * zeros_padding
417
+
418
+ uncond_indicator = uncond_mask = None
419
+ if do_classifier_free_guidance:
420
+ uncond_indicator = latents.new_zeros(1, 1, latents.size(2), 1, 1)
421
+ uncond_indicator[:, :, :num_cond_latent_frames] = 1.0
422
+ uncond_mask = uncond_indicator * ones_padding + (1 - uncond_indicator) * zeros_padding
423
+
424
+ return latents, init_latents, cond_indicator, uncond_indicator, cond_mask, uncond_mask
425
+
426
+ # Copied from diffusers.pipelines.cosmos.pipeline_cosmos_text2world.CosmosTextToWorldPipeline.check_inputs
427
+ def check_inputs(
428
+ self,
429
+ prompt,
430
+ height,
431
+ width,
432
+ prompt_embeds=None,
433
+ callback_on_step_end_tensor_inputs=None,
434
+ ):
435
+ if height % 16 != 0 or width % 16 != 0:
436
+ raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
437
+
438
+ if callback_on_step_end_tensor_inputs is not None and not all(
439
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
440
+ ):
441
+ raise ValueError(
442
+ 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]}"
443
+ )
444
+
445
+ if prompt is not None and prompt_embeds is not None:
446
+ raise ValueError(
447
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
448
+ " only forward one of the two."
449
+ )
450
+ elif prompt is None and prompt_embeds is None:
451
+ raise ValueError(
452
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
453
+ )
454
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
455
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
456
+
457
+ @property
458
+ def guidance_scale(self):
459
+ return self._guidance_scale
460
+
461
+ @property
462
+ def do_classifier_free_guidance(self):
463
+ return self._guidance_scale > 1.0
464
+
465
+ @property
466
+ def num_timesteps(self):
467
+ return self._num_timesteps
468
+
469
+ @property
470
+ def current_timestep(self):
471
+ return self._current_timestep
472
+
473
+ @property
474
+ def interrupt(self):
475
+ return self._interrupt
476
+
477
+ @torch.no_grad()
478
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
479
+ def __call__(
480
+ self,
481
+ image: PipelineImageInput = None,
482
+ video: List[PipelineImageInput] = None,
483
+ prompt: Union[str, List[str]] = None,
484
+ negative_prompt: Optional[Union[str, List[str]]] = None,
485
+ height: int = 704,
486
+ width: int = 1280,
487
+ num_frames: int = 93,
488
+ num_inference_steps: int = 35,
489
+ guidance_scale: float = 7.0,
490
+ fps: int = 16,
491
+ num_videos_per_prompt: Optional[int] = 1,
492
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
493
+ latents: Optional[torch.Tensor] = None,
494
+ prompt_embeds: Optional[torch.Tensor] = None,
495
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
496
+ output_type: Optional[str] = "pil",
497
+ return_dict: bool = True,
498
+ callback_on_step_end: Optional[
499
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
500
+ ] = None,
501
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
502
+ max_sequence_length: int = 512,
503
+ sigma_conditioning: float = 0.0001,
504
+ ):
505
+ r"""
506
+ The call function to the pipeline for generation.
507
+
508
+ Args:
509
+ image (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, *optional*):
510
+ The image to be used as a conditioning input for the video generation.
511
+ video (`List[PIL.Image.Image]`, `np.ndarray`, `torch.Tensor`, *optional*):
512
+ The video to be used as a conditioning input for the video generation.
513
+ prompt (`str` or `List[str]`, *optional*):
514
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
515
+ instead.
516
+ height (`int`, defaults to `704`):
517
+ The height in pixels of the generated image.
518
+ width (`int`, defaults to `1280`):
519
+ The width in pixels of the generated image.
520
+ num_frames (`int`, defaults to `93`):
521
+ The number of frames in the generated video.
522
+ num_inference_steps (`int`, defaults to `35`):
523
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
524
+ expense of slower inference.
525
+ guidance_scale (`float`, defaults to `7.0`):
526
+ Guidance scale as defined in [Classifier-Free Diffusion
527
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
528
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
529
+ `guidance_scale > 1`.
530
+ fps (`int`, defaults to `16`):
531
+ The frames per second of the generated video.
532
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
533
+ The number of images to generate per prompt.
534
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
535
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
536
+ generation deterministic.
537
+ latents (`torch.Tensor`, *optional*):
538
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
539
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
540
+ tensor is generated by sampling using the supplied random `generator`.
541
+ prompt_embeds (`torch.Tensor`, *optional*):
542
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
543
+ provided, text embeddings will be generated from `prompt` input argument.
544
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
545
+ Pre-generated negative text embeddings. For PixArt-Sigma this negative prompt should be "". If not
546
+ provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
547
+ output_type (`str`, *optional*, defaults to `"pil"`):
548
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
549
+ return_dict (`bool`, *optional*, defaults to `True`):
550
+ Whether or not to return a [`CosmosPipelineOutput`] instead of a plain tuple.
551
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
552
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
553
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
554
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
555
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
556
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
557
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
558
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
559
+ `._callback_tensor_inputs` attribute of your pipeline class.
560
+ max_sequence_length (`int`, defaults to `512`):
561
+ The maximum number of tokens in the prompt. If the prompt exceeds this length, it will be truncated. If
562
+ the prompt is shorter than this length, it will be padded.
563
+ sigma_conditioning (`float`, defaults to `0.0001`):
564
+ The sigma value used for scaling conditioning latents. Ideally, it should not be changed or should be
565
+ set to a small value close to zero.
566
+
567
+ Examples:
568
+
569
+ Returns:
570
+ [`~CosmosPipelineOutput`] or `tuple`:
571
+ If `return_dict` is `True`, [`CosmosPipelineOutput`] is returned, otherwise a `tuple` is returned where
572
+ the first element is a list with the generated images and the second element is a list of `bool`s
573
+ indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
574
+ """
575
+
576
+ if self.safety_checker is None:
577
+ raise ValueError(
578
+ f"You have disabled the safety checker for {self.__class__}. This is in violation of the "
579
+ "[NVIDIA Open Model License Agreement](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license). "
580
+ f"Please ensure that you are compliant with the license agreement."
581
+ )
582
+
583
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
584
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
585
+
586
+ # 1. Check inputs. Raise error if not correct
587
+ self.check_inputs(prompt, height, width, prompt_embeds, callback_on_step_end_tensor_inputs)
588
+
589
+ self._guidance_scale = guidance_scale
590
+ self._current_timestep = None
591
+ self._interrupt = False
592
+
593
+ device = self._execution_device
594
+
595
+ if self.safety_checker is not None:
596
+ self.safety_checker.to(device)
597
+ if prompt is not None:
598
+ prompt_list = [prompt] if isinstance(prompt, str) else prompt
599
+ for p in prompt_list:
600
+ if not self.safety_checker.check_text_safety(p):
601
+ raise ValueError(
602
+ f"Cosmos Guardrail detected unsafe text in the prompt: {p}. Please ensure that the "
603
+ f"prompt abides by the NVIDIA Open Model License Agreement."
604
+ )
605
+ self.safety_checker.to("cpu")
606
+
607
+ # 2. Define call parameters
608
+ if prompt is not None and isinstance(prompt, str):
609
+ batch_size = 1
610
+ elif prompt is not None and isinstance(prompt, list):
611
+ batch_size = len(prompt)
612
+ else:
613
+ batch_size = prompt_embeds.shape[0]
614
+
615
+ # 3. Encode input prompt
616
+ (
617
+ prompt_embeds,
618
+ negative_prompt_embeds,
619
+ ) = self.encode_prompt(
620
+ prompt=prompt,
621
+ negative_prompt=negative_prompt,
622
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
623
+ num_videos_per_prompt=num_videos_per_prompt,
624
+ prompt_embeds=prompt_embeds,
625
+ negative_prompt_embeds=negative_prompt_embeds,
626
+ device=device,
627
+ max_sequence_length=max_sequence_length,
628
+ )
629
+
630
+ # 4. Prepare timesteps
631
+ sigmas_dtype = torch.float32 if torch.backends.mps.is_available() else torch.float64
632
+ sigmas = torch.linspace(0, 1, num_inference_steps, dtype=sigmas_dtype)
633
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, device=device, sigmas=sigmas)
634
+ if self.scheduler.config.final_sigmas_type == "sigma_min":
635
+ # Replace the last sigma (which is zero) with the minimum sigma value
636
+ self.scheduler.sigmas[-1] = self.scheduler.sigmas[-2]
637
+
638
+ # 5. Prepare latent variables
639
+ vae_dtype = self.vae.dtype
640
+ transformer_dtype = self.transformer.dtype
641
+
642
+ if image is not None:
643
+ video = self.video_processor.preprocess(image, height, width).unsqueeze(2)
644
+ else:
645
+ video = self.video_processor.preprocess_video(video, height, width)
646
+ video = video.to(device=device, dtype=vae_dtype)
647
+
648
+ num_channels_latents = self.transformer.config.in_channels - 1
649
+ latents, conditioning_latents, cond_indicator, uncond_indicator, cond_mask, uncond_mask = self.prepare_latents(
650
+ video,
651
+ batch_size * num_videos_per_prompt,
652
+ num_channels_latents,
653
+ height,
654
+ width,
655
+ num_frames,
656
+ self.do_classifier_free_guidance,
657
+ torch.float32,
658
+ device,
659
+ generator,
660
+ latents,
661
+ )
662
+ unconditioning_latents = None
663
+
664
+ cond_mask = cond_mask.to(transformer_dtype)
665
+ if self.do_classifier_free_guidance:
666
+ uncond_mask = uncond_mask.to(transformer_dtype)
667
+ unconditioning_latents = conditioning_latents
668
+
669
+ padding_mask = latents.new_zeros(1, 1, height, width, dtype=transformer_dtype)
670
+ sigma_conditioning = torch.tensor(sigma_conditioning, dtype=torch.float32, device=device)
671
+ t_conditioning = sigma_conditioning / (sigma_conditioning + 1)
672
+
673
+ # 6. Denoising loop
674
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
675
+ self._num_timesteps = len(timesteps)
676
+
677
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
678
+ for i, t in enumerate(timesteps):
679
+ if self.interrupt:
680
+ continue
681
+
682
+ self._current_timestep = t
683
+ current_sigma = self.scheduler.sigmas[i]
684
+
685
+ current_t = current_sigma / (current_sigma + 1)
686
+ c_in = 1 - current_t
687
+ c_skip = 1 - current_t
688
+ c_out = -current_t
689
+ timestep = current_t.view(1, 1, 1, 1, 1).expand(
690
+ latents.size(0), -1, latents.size(2), -1, -1
691
+ ) # [B, 1, T, 1, 1]
692
+
693
+ cond_latent = latents * c_in
694
+ cond_latent = cond_indicator * conditioning_latents + (1 - cond_indicator) * cond_latent
695
+ cond_latent = cond_latent.to(transformer_dtype)
696
+ cond_timestep = cond_indicator * t_conditioning + (1 - cond_indicator) * timestep
697
+ cond_timestep = cond_timestep.to(transformer_dtype)
698
+
699
+ noise_pred = self.transformer(
700
+ hidden_states=cond_latent,
701
+ timestep=cond_timestep,
702
+ encoder_hidden_states=prompt_embeds,
703
+ fps=fps,
704
+ condition_mask=cond_mask,
705
+ padding_mask=padding_mask,
706
+ return_dict=False,
707
+ )[0]
708
+ noise_pred = (c_skip * latents + c_out * noise_pred.float()).to(transformer_dtype)
709
+ noise_pred = cond_indicator * conditioning_latents + (1 - cond_indicator) * noise_pred
710
+
711
+ if self.do_classifier_free_guidance:
712
+ uncond_latent = latents * c_in
713
+ uncond_latent = uncond_indicator * unconditioning_latents + (1 - uncond_indicator) * uncond_latent
714
+ uncond_latent = uncond_latent.to(transformer_dtype)
715
+ uncond_timestep = uncond_indicator * t_conditioning + (1 - uncond_indicator) * timestep
716
+ uncond_timestep = uncond_timestep.to(transformer_dtype)
717
+
718
+ noise_pred_uncond = self.transformer(
719
+ hidden_states=uncond_latent,
720
+ timestep=uncond_timestep,
721
+ encoder_hidden_states=negative_prompt_embeds,
722
+ fps=fps,
723
+ condition_mask=uncond_mask,
724
+ padding_mask=padding_mask,
725
+ return_dict=False,
726
+ )[0]
727
+ noise_pred_uncond = (c_skip * latents + c_out * noise_pred_uncond.float()).to(transformer_dtype)
728
+ noise_pred_uncond = (
729
+ uncond_indicator * unconditioning_latents + (1 - uncond_indicator) * noise_pred_uncond
730
+ )
731
+ noise_pred = noise_pred + self.guidance_scale * (noise_pred - noise_pred_uncond)
732
+
733
+ noise_pred = (latents - noise_pred) / current_sigma
734
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
735
+
736
+ if callback_on_step_end is not None:
737
+ callback_kwargs = {}
738
+ for k in callback_on_step_end_tensor_inputs:
739
+ callback_kwargs[k] = locals()[k]
740
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
741
+
742
+ latents = callback_outputs.pop("latents", latents)
743
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
744
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
745
+
746
+ # call the callback, if provided
747
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
748
+ progress_bar.update()
749
+
750
+ if XLA_AVAILABLE:
751
+ xm.mark_step()
752
+
753
+ self._current_timestep = None
754
+
755
+ if not output_type == "latent":
756
+ latents_mean = (
757
+ torch.tensor(self.vae.config.latents_mean)
758
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
759
+ .to(latents.device, latents.dtype)
760
+ )
761
+ latents_std = (
762
+ torch.tensor(self.vae.config.latents_std)
763
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
764
+ .to(latents.device, latents.dtype)
765
+ )
766
+ latents = latents * latents_std / self.scheduler.config.sigma_data + latents_mean
767
+ video = self.vae.decode(latents.to(self.vae.dtype), return_dict=False)[0]
768
+
769
+ if self.safety_checker is not None:
770
+ self.safety_checker.to(device)
771
+ video = self.video_processor.postprocess_video(video, output_type="np")
772
+ video = (video * 255).astype(np.uint8)
773
+ video_batch = []
774
+ for vid in video:
775
+ vid = self.safety_checker.check_video_safety(vid)
776
+ video_batch.append(vid)
777
+ video = np.stack(video_batch).astype(np.float32) / 255.0 * 2 - 1
778
+ video = torch.from_numpy(video).permute(0, 4, 1, 2, 3)
779
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
780
+ self.safety_checker.to("cpu")
781
+ else:
782
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
783
+ else:
784
+ video = latents
785
+
786
+ # Offload all models
787
+ self.maybe_free_model_hooks()
788
+
789
+ if not return_dict:
790
+ return (video,)
791
+
792
+ return CosmosPipelineOutput(frames=video)