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,826 @@
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 AutoencoderKLCosmos, CosmosTransformer3DModel
25
+ from ...schedulers import EDMEulerScheduler
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
+ Image conditioning:
57
+
58
+ ```python
59
+ >>> import torch
60
+ >>> from diffusers import CosmosVideoToWorldPipeline
61
+ >>> from diffusers.utils import export_to_video, load_image
62
+
63
+ >>> model_id = "nvidia/Cosmos-1.0-Diffusion-7B-Video2World"
64
+ >>> pipe = CosmosVideoToWorldPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
65
+ >>> pipe.to("cuda")
66
+
67
+ >>> prompt = "The video depicts a long, straight highway stretching into the distance, flanked by metal guardrails. The road is divided into multiple lanes, with a few vehicles visible in the far distance. The surrounding landscape features dry, grassy fields on one side and rolling hills on the other. The sky is mostly clear with a few scattered clouds, suggesting a bright, sunny day."
68
+ >>> image = load_image(
69
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cosmos/cosmos-video2world-input.jpg"
70
+ ... )
71
+
72
+ >>> video = pipe(image=image, prompt=prompt).frames[0]
73
+ >>> export_to_video(video, "output.mp4", fps=30)
74
+ ```
75
+
76
+ Video conditioning:
77
+
78
+ ```python
79
+ >>> import torch
80
+ >>> from diffusers import CosmosVideoToWorldPipeline
81
+ >>> from diffusers.utils import export_to_video, load_video
82
+
83
+ >>> model_id = "nvidia/Cosmos-1.0-Diffusion-7B-Video2World"
84
+ >>> pipe = CosmosVideoToWorldPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
85
+ >>> pipe.transformer = torch.compile(pipe.transformer)
86
+ >>> pipe.to("cuda")
87
+
88
+ >>> prompt = "The video depicts a winding mountain road covered in snow, with a single vehicle traveling along it. The road is flanked by steep, rocky cliffs and sparse vegetation. The landscape is characterized by rugged terrain and a river visible in the distance. The scene captures the solitude and beauty of a winter drive through a mountainous region."
89
+ >>> video = load_video(
90
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cosmos/cosmos-video2world-input-vid.mp4"
91
+ ... )[
92
+ ... :21
93
+ ... ] # This example uses only the first 21 frames
94
+
95
+ >>> video = pipe(video=video, prompt=prompt).frames[0]
96
+ >>> export_to_video(video, "output.mp4", fps=30)
97
+ ```
98
+ """
99
+
100
+
101
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
102
+ def retrieve_timesteps(
103
+ scheduler,
104
+ num_inference_steps: Optional[int] = None,
105
+ device: Optional[Union[str, torch.device]] = None,
106
+ timesteps: Optional[List[int]] = None,
107
+ sigmas: Optional[List[float]] = None,
108
+ **kwargs,
109
+ ):
110
+ r"""
111
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
112
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
113
+
114
+ Args:
115
+ scheduler (`SchedulerMixin`):
116
+ The scheduler to get timesteps from.
117
+ num_inference_steps (`int`):
118
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
119
+ must be `None`.
120
+ device (`str` or `torch.device`, *optional*):
121
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
122
+ timesteps (`List[int]`, *optional*):
123
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
124
+ `num_inference_steps` and `sigmas` must be `None`.
125
+ sigmas (`List[float]`, *optional*):
126
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
127
+ `num_inference_steps` and `timesteps` must be `None`.
128
+
129
+ Returns:
130
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
131
+ second element is the number of inference steps.
132
+ """
133
+ if timesteps is not None and sigmas is not None:
134
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
135
+ if timesteps is not None:
136
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
137
+ if not accepts_timesteps:
138
+ raise ValueError(
139
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
140
+ f" timestep schedules. Please check whether you are using the correct scheduler."
141
+ )
142
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
143
+ timesteps = scheduler.timesteps
144
+ num_inference_steps = len(timesteps)
145
+ elif sigmas is not None:
146
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
147
+ if not accept_sigmas:
148
+ raise ValueError(
149
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
150
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
151
+ )
152
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
153
+ timesteps = scheduler.timesteps
154
+ num_inference_steps = len(timesteps)
155
+ else:
156
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
157
+ timesteps = scheduler.timesteps
158
+ return timesteps, num_inference_steps
159
+
160
+
161
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
162
+ def retrieve_latents(
163
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
164
+ ):
165
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
166
+ return encoder_output.latent_dist.sample(generator)
167
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
168
+ return encoder_output.latent_dist.mode()
169
+ elif hasattr(encoder_output, "latents"):
170
+ return encoder_output.latents
171
+ else:
172
+ raise AttributeError("Could not access latents of provided encoder_output")
173
+
174
+
175
+ class CosmosVideoToWorldPipeline(DiffusionPipeline):
176
+ r"""
177
+ Pipeline for image-to-world and video-to-world generation using [Cosmos
178
+ Predict-1](https://github.com/nvidia-cosmos/cosmos-predict1).
179
+
180
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
181
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
182
+
183
+ Args:
184
+ text_encoder ([`T5EncoderModel`]):
185
+ Frozen text-encoder. Cosmos uses
186
+ [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel); specifically the
187
+ [t5-11b](https://huggingface.co/google-t5/t5-11b) variant.
188
+ tokenizer (`T5TokenizerFast`):
189
+ Tokenizer of class
190
+ [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
191
+ transformer ([`CosmosTransformer3DModel`]):
192
+ Conditional Transformer to denoise the encoded image latents.
193
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
194
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
195
+ vae ([`AutoencoderKLCosmos`]):
196
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
197
+ """
198
+
199
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
200
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
201
+ # We mark safety_checker as optional here to get around some test failures, but it is not really optional
202
+ _optional_components = ["safety_checker"]
203
+
204
+ def __init__(
205
+ self,
206
+ text_encoder: T5EncoderModel,
207
+ tokenizer: T5TokenizerFast,
208
+ transformer: CosmosTransformer3DModel,
209
+ vae: AutoencoderKLCosmos,
210
+ scheduler: EDMEulerScheduler,
211
+ safety_checker: CosmosSafetyChecker = None,
212
+ ):
213
+ super().__init__()
214
+
215
+ if safety_checker is None:
216
+ safety_checker = CosmosSafetyChecker()
217
+
218
+ self.register_modules(
219
+ vae=vae,
220
+ text_encoder=text_encoder,
221
+ tokenizer=tokenizer,
222
+ transformer=transformer,
223
+ scheduler=scheduler,
224
+ safety_checker=safety_checker,
225
+ )
226
+
227
+ self.vae_scale_factor_temporal = (
228
+ self.vae.config.temporal_compression_ratio if getattr(self, "vae", None) else 8
229
+ )
230
+ self.vae_scale_factor_spatial = self.vae.config.spatial_compression_ratio if getattr(self, "vae", None) else 8
231
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
232
+
233
+ # Copied from diffusers.pipelines.cosmos.pipeline_cosmos_text2world.CosmosTextToWorldPipeline._get_t5_prompt_embeds
234
+ def _get_t5_prompt_embeds(
235
+ self,
236
+ prompt: Union[str, List[str]] = None,
237
+ max_sequence_length: int = 512,
238
+ device: Optional[torch.device] = None,
239
+ dtype: Optional[torch.dtype] = None,
240
+ ):
241
+ device = device or self._execution_device
242
+ dtype = dtype or self.text_encoder.dtype
243
+ prompt = [prompt] if isinstance(prompt, str) else prompt
244
+
245
+ text_inputs = self.tokenizer(
246
+ prompt,
247
+ padding="max_length",
248
+ max_length=max_sequence_length,
249
+ truncation=True,
250
+ return_tensors="pt",
251
+ return_length=True,
252
+ return_offsets_mapping=False,
253
+ )
254
+ text_input_ids = text_inputs.input_ids
255
+ prompt_attention_mask = text_inputs.attention_mask.bool().to(device)
256
+
257
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
258
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
259
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
260
+ logger.warning(
261
+ "The following part of your input was truncated because `max_sequence_length` is set to "
262
+ f" {max_sequence_length} tokens: {removed_text}"
263
+ )
264
+
265
+ prompt_embeds = self.text_encoder(
266
+ text_input_ids.to(device), attention_mask=prompt_attention_mask
267
+ ).last_hidden_state
268
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
269
+
270
+ lengths = prompt_attention_mask.sum(dim=1).cpu()
271
+ for i, length in enumerate(lengths):
272
+ prompt_embeds[i, length:] = 0
273
+
274
+ return prompt_embeds
275
+
276
+ # Copied from diffusers.pipelines.cosmos.pipeline_cosmos_text2world.CosmosTextToWorldPipeline.encode_prompt
277
+ def encode_prompt(
278
+ self,
279
+ prompt: Union[str, List[str]],
280
+ negative_prompt: Optional[Union[str, List[str]]] = None,
281
+ do_classifier_free_guidance: bool = True,
282
+ num_videos_per_prompt: int = 1,
283
+ prompt_embeds: Optional[torch.Tensor] = None,
284
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
285
+ max_sequence_length: int = 512,
286
+ device: Optional[torch.device] = None,
287
+ dtype: Optional[torch.dtype] = None,
288
+ ):
289
+ r"""
290
+ Encodes the prompt into text encoder hidden states.
291
+
292
+ Args:
293
+ prompt (`str` or `List[str]`, *optional*):
294
+ prompt to be encoded
295
+ negative_prompt (`str` or `List[str]`, *optional*):
296
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
297
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
298
+ less than `1`).
299
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
300
+ Whether to use classifier free guidance or not.
301
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
302
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
303
+ prompt_embeds (`torch.Tensor`, *optional*):
304
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
305
+ provided, text embeddings will be generated from `prompt` input argument.
306
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
307
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
308
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
309
+ argument.
310
+ device: (`torch.device`, *optional*):
311
+ torch device
312
+ dtype: (`torch.dtype`, *optional*):
313
+ torch dtype
314
+ """
315
+ device = device or self._execution_device
316
+
317
+ prompt = [prompt] if isinstance(prompt, str) else prompt
318
+ if prompt is not None:
319
+ batch_size = len(prompt)
320
+ else:
321
+ batch_size = prompt_embeds.shape[0]
322
+
323
+ if prompt_embeds is None:
324
+ prompt_embeds = self._get_t5_prompt_embeds(
325
+ prompt=prompt, max_sequence_length=max_sequence_length, device=device, dtype=dtype
326
+ )
327
+
328
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
329
+ _, seq_len, _ = prompt_embeds.shape
330
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
331
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
332
+
333
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
334
+ negative_prompt = negative_prompt or ""
335
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
336
+
337
+ if prompt is not None and type(prompt) is not type(negative_prompt):
338
+ raise TypeError(
339
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
340
+ f" {type(prompt)}."
341
+ )
342
+ elif batch_size != len(negative_prompt):
343
+ raise ValueError(
344
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
345
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
346
+ " the batch size of `prompt`."
347
+ )
348
+
349
+ negative_prompt_embeds = self._get_t5_prompt_embeds(
350
+ prompt=negative_prompt, max_sequence_length=max_sequence_length, device=device, dtype=dtype
351
+ )
352
+
353
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
354
+ _, seq_len, _ = negative_prompt_embeds.shape
355
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_videos_per_prompt, 1)
356
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
357
+
358
+ return prompt_embeds, negative_prompt_embeds
359
+
360
+ def prepare_latents(
361
+ self,
362
+ video: torch.Tensor,
363
+ batch_size: int,
364
+ num_channels_latents: 16,
365
+ height: int = 704,
366
+ width: int = 1280,
367
+ num_frames: int = 121,
368
+ do_classifier_free_guidance: bool = True,
369
+ input_frames_guidance: bool = False,
370
+ dtype: Optional[torch.dtype] = None,
371
+ device: Optional[torch.device] = None,
372
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
373
+ latents: Optional[torch.Tensor] = None,
374
+ ) -> torch.Tensor:
375
+ if isinstance(generator, list) and len(generator) != batch_size:
376
+ raise ValueError(
377
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
378
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
379
+ )
380
+
381
+ num_cond_frames = video.size(2)
382
+ if num_cond_frames >= num_frames:
383
+ # Take the last `num_frames` frames for conditioning
384
+ num_cond_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
385
+ video = video[:, :, -num_frames:]
386
+ else:
387
+ num_cond_latent_frames = (num_cond_frames - 1) // self.vae_scale_factor_temporal + 1
388
+ num_padding_frames = num_frames - num_cond_frames
389
+ padding = video.new_zeros(video.size(0), video.size(1), num_padding_frames, video.size(3), video.size(4))
390
+ video = torch.cat([video, padding], dim=2)
391
+
392
+ if isinstance(generator, list):
393
+ init_latents = [
394
+ retrieve_latents(self.vae.encode(video[i].unsqueeze(0)), generator=generator[i])
395
+ for i in range(batch_size)
396
+ ]
397
+ else:
398
+ init_latents = [retrieve_latents(self.vae.encode(vid.unsqueeze(0)), generator) for vid in video]
399
+
400
+ init_latents = torch.cat(init_latents, dim=0).to(dtype)
401
+
402
+ if self.vae.config.latents_mean is not None:
403
+ latents_mean, latents_std = self.vae.config.latents_mean, self.vae.config.latents_std
404
+ latents_mean = (
405
+ torch.tensor(latents_mean)
406
+ .view(1, self.vae.config.latent_channels, -1, 1, 1)[:, :, : init_latents.size(2)]
407
+ .to(init_latents)
408
+ )
409
+ latents_std = (
410
+ torch.tensor(latents_std)
411
+ .view(1, self.vae.config.latent_channels, -1, 1, 1)[:, :, : init_latents.size(2)]
412
+ .to(init_latents)
413
+ )
414
+ init_latents = (init_latents - latents_mean) * self.scheduler.config.sigma_data / latents_std
415
+ else:
416
+ init_latents = init_latents * self.scheduler.config.sigma_data
417
+
418
+ num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
419
+ latent_height = height // self.vae_scale_factor_spatial
420
+ latent_width = width // self.vae_scale_factor_spatial
421
+ shape = (batch_size, num_channels_latents, num_latent_frames, latent_height, latent_width)
422
+
423
+ if latents is None:
424
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
425
+ else:
426
+ latents = latents.to(device=device, dtype=dtype)
427
+
428
+ latents = latents * self.scheduler.config.sigma_max
429
+
430
+ padding_shape = (batch_size, 1, num_latent_frames, latent_height, latent_width)
431
+ ones_padding = latents.new_ones(padding_shape)
432
+ zeros_padding = latents.new_zeros(padding_shape)
433
+
434
+ cond_indicator = latents.new_zeros(1, 1, latents.size(2), 1, 1)
435
+ cond_indicator[:, :, :num_cond_latent_frames] = 1.0
436
+ cond_mask = cond_indicator * ones_padding + (1 - cond_indicator) * zeros_padding
437
+
438
+ uncond_indicator = uncond_mask = None
439
+ if do_classifier_free_guidance:
440
+ uncond_indicator = latents.new_zeros(1, 1, latents.size(2), 1, 1)
441
+ uncond_indicator[:, :, :num_cond_latent_frames] = 1.0
442
+ uncond_mask = zeros_padding
443
+ if not input_frames_guidance:
444
+ uncond_mask = uncond_indicator * ones_padding + (1 - uncond_indicator) * zeros_padding
445
+
446
+ return latents, init_latents, cond_indicator, uncond_indicator, cond_mask, uncond_mask
447
+
448
+ def check_inputs(
449
+ self,
450
+ prompt,
451
+ height,
452
+ width,
453
+ prompt_embeds=None,
454
+ callback_on_step_end_tensor_inputs=None,
455
+ image=None,
456
+ video=None,
457
+ ):
458
+ if height % 16 != 0 or width % 16 != 0:
459
+ raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
460
+
461
+ if callback_on_step_end_tensor_inputs is not None and not all(
462
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
463
+ ):
464
+ raise ValueError(
465
+ 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]}"
466
+ )
467
+
468
+ if prompt is not None and prompt_embeds is not None:
469
+ raise ValueError(
470
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
471
+ " only forward one of the two."
472
+ )
473
+ elif prompt is None and prompt_embeds is None:
474
+ raise ValueError(
475
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
476
+ )
477
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
478
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
479
+
480
+ if image is None and video is None:
481
+ raise ValueError("Either `image` or `video` has to be provided.")
482
+ if image is not None and video is not None:
483
+ raise ValueError("Only one of `image` or `video` has to be provided.")
484
+
485
+ @property
486
+ def guidance_scale(self):
487
+ return self._guidance_scale
488
+
489
+ @property
490
+ def do_classifier_free_guidance(self):
491
+ return self._guidance_scale > 1.0
492
+
493
+ @property
494
+ def num_timesteps(self):
495
+ return self._num_timesteps
496
+
497
+ @property
498
+ def current_timestep(self):
499
+ return self._current_timestep
500
+
501
+ @property
502
+ def interrupt(self):
503
+ return self._interrupt
504
+
505
+ @torch.no_grad()
506
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
507
+ def __call__(
508
+ self,
509
+ image: PipelineImageInput = None,
510
+ video: List[PipelineImageInput] = None,
511
+ prompt: Union[str, List[str]] = None,
512
+ negative_prompt: Optional[Union[str, List[str]]] = None,
513
+ height: int = 704,
514
+ width: int = 1280,
515
+ num_frames: int = 121,
516
+ num_inference_steps: int = 36,
517
+ guidance_scale: float = 7.0,
518
+ input_frames_guidance: bool = False,
519
+ augment_sigma: float = 0.001,
520
+ fps: int = 30,
521
+ num_videos_per_prompt: Optional[int] = 1,
522
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
523
+ latents: Optional[torch.Tensor] = None,
524
+ prompt_embeds: Optional[torch.Tensor] = None,
525
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
526
+ output_type: Optional[str] = "pil",
527
+ return_dict: bool = True,
528
+ callback_on_step_end: Optional[
529
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
530
+ ] = None,
531
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
532
+ max_sequence_length: int = 512,
533
+ ):
534
+ r"""
535
+ The call function to the pipeline for generation.
536
+
537
+ Args:
538
+ prompt (`str` or `List[str]`, *optional*):
539
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
540
+ instead.
541
+ height (`int`, defaults to `720`):
542
+ The height in pixels of the generated image.
543
+ width (`int`, defaults to `1280`):
544
+ The width in pixels of the generated image.
545
+ num_frames (`int`, defaults to `121`):
546
+ The number of frames in the generated video.
547
+ num_inference_steps (`int`, defaults to `36`):
548
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
549
+ expense of slower inference.
550
+ guidance_scale (`float`, defaults to `7.0`):
551
+ Guidance scale as defined in [Classifier-Free Diffusion
552
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
553
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
554
+ `guidance_scale > 1`.
555
+ fps (`int`, defaults to `30`):
556
+ The frames per second of the generated video.
557
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
558
+ The number of images to generate per prompt.
559
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
560
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
561
+ generation deterministic.
562
+ latents (`torch.Tensor`, *optional*):
563
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
564
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
565
+ tensor is generated by sampling using the supplied random `generator`.
566
+ prompt_embeds (`torch.Tensor`, *optional*):
567
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
568
+ provided, text embeddings will be generated from `prompt` input argument.
569
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
570
+ Pre-generated negative text embeddings. For PixArt-Sigma this negative prompt should be "". If not
571
+ provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
572
+ output_type (`str`, *optional*, defaults to `"pil"`):
573
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
574
+ return_dict (`bool`, *optional*, defaults to `True`):
575
+ Whether or not to return a [`CosmosPipelineOutput`] instead of a plain tuple.
576
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
577
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
578
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
579
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
580
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
581
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
582
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
583
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
584
+ `._callback_tensor_inputs` attribute of your pipeline class.
585
+
586
+ Examples:
587
+
588
+ Returns:
589
+ [`~CosmosPipelineOutput`] or `tuple`:
590
+ If `return_dict` is `True`, [`CosmosPipelineOutput`] is returned, otherwise a `tuple` is returned where
591
+ the first element is a list with the generated images and the second element is a list of `bool`s
592
+ indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
593
+ """
594
+
595
+ if self.safety_checker is None:
596
+ raise ValueError(
597
+ f"You have disabled the safety checker for {self.__class__}. This is in violation of the "
598
+ "[NVIDIA Open Model License Agreement](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license). "
599
+ f"Please ensure that you are compliant with the license agreement."
600
+ )
601
+
602
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
603
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
604
+
605
+ # 1. Check inputs. Raise error if not correct
606
+ self.check_inputs(prompt, height, width, prompt_embeds, callback_on_step_end_tensor_inputs, image, video)
607
+
608
+ self._guidance_scale = guidance_scale
609
+ self._current_timestep = None
610
+ self._interrupt = False
611
+
612
+ device = self._execution_device
613
+
614
+ if self.safety_checker is not None:
615
+ self.safety_checker.to(device)
616
+ if prompt is not None:
617
+ prompt_list = [prompt] if isinstance(prompt, str) else prompt
618
+ for p in prompt_list:
619
+ if not self.safety_checker.check_text_safety(p):
620
+ raise ValueError(
621
+ f"Cosmos Guardrail detected unsafe text in the prompt: {p}. Please ensure that the "
622
+ f"prompt abides by the NVIDIA Open Model License Agreement."
623
+ )
624
+ self.safety_checker.to("cpu")
625
+
626
+ # 2. Define call parameters
627
+ if prompt is not None and isinstance(prompt, str):
628
+ batch_size = 1
629
+ elif prompt is not None and isinstance(prompt, list):
630
+ batch_size = len(prompt)
631
+ else:
632
+ batch_size = prompt_embeds.shape[0]
633
+
634
+ # 3. Encode input prompt
635
+ (
636
+ prompt_embeds,
637
+ negative_prompt_embeds,
638
+ ) = self.encode_prompt(
639
+ prompt=prompt,
640
+ negative_prompt=negative_prompt,
641
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
642
+ num_videos_per_prompt=num_videos_per_prompt,
643
+ prompt_embeds=prompt_embeds,
644
+ negative_prompt_embeds=negative_prompt_embeds,
645
+ device=device,
646
+ max_sequence_length=max_sequence_length,
647
+ )
648
+
649
+ # 4. Prepare timesteps
650
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device)
651
+
652
+ # 5. Prepare latent variables
653
+ vae_dtype = self.vae.dtype
654
+ transformer_dtype = self.transformer.dtype
655
+
656
+ if image is not None:
657
+ video = self.video_processor.preprocess(image, height, width).unsqueeze(2)
658
+ else:
659
+ video = self.video_processor.preprocess_video(video, height, width)
660
+ video = video.to(device=device, dtype=vae_dtype)
661
+
662
+ num_channels_latents = self.transformer.config.in_channels - 1
663
+ latents, conditioning_latents, cond_indicator, uncond_indicator, cond_mask, uncond_mask = self.prepare_latents(
664
+ video,
665
+ batch_size * num_videos_per_prompt,
666
+ num_channels_latents,
667
+ height,
668
+ width,
669
+ num_frames,
670
+ self.do_classifier_free_guidance,
671
+ input_frames_guidance,
672
+ torch.float32,
673
+ device,
674
+ generator,
675
+ latents,
676
+ )
677
+ cond_mask = cond_mask.to(transformer_dtype)
678
+ if self.do_classifier_free_guidance:
679
+ uncond_mask = uncond_mask.to(transformer_dtype)
680
+
681
+ augment_sigma = torch.tensor([augment_sigma], device=device, dtype=torch.float32)
682
+ padding_mask = latents.new_zeros(1, 1, height, width, dtype=transformer_dtype)
683
+
684
+ # 6. Denoising loop
685
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
686
+ self._num_timesteps = len(timesteps)
687
+
688
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
689
+ for i, t in enumerate(timesteps):
690
+ if self.interrupt:
691
+ continue
692
+
693
+ self._current_timestep = t
694
+ timestep = t.expand(latents.shape[0]).to(transformer_dtype)
695
+
696
+ current_sigma = self.scheduler.sigmas[i]
697
+ is_augment_sigma_greater = augment_sigma >= current_sigma
698
+
699
+ c_in_augment = self.scheduler._get_conditioning_c_in(augment_sigma)
700
+ c_in_original = self.scheduler._get_conditioning_c_in(current_sigma)
701
+
702
+ current_cond_indicator = cond_indicator * 0 if is_augment_sigma_greater else cond_indicator
703
+ cond_noise = randn_tensor(latents.shape, generator=generator, device=device, dtype=torch.float32)
704
+ cond_latent = conditioning_latents + cond_noise * augment_sigma[:, None, None, None, None]
705
+ cond_latent = cond_latent * c_in_augment / c_in_original
706
+ cond_latent = current_cond_indicator * cond_latent + (1 - current_cond_indicator) * latents
707
+ cond_latent = self.scheduler.scale_model_input(cond_latent, t)
708
+ cond_latent = cond_latent.to(transformer_dtype)
709
+
710
+ noise_pred = self.transformer(
711
+ hidden_states=cond_latent,
712
+ timestep=timestep,
713
+ encoder_hidden_states=prompt_embeds,
714
+ fps=fps,
715
+ condition_mask=cond_mask,
716
+ padding_mask=padding_mask,
717
+ return_dict=False,
718
+ )[0]
719
+
720
+ sample = latents
721
+ if self.do_classifier_free_guidance:
722
+ current_uncond_indicator = uncond_indicator * 0 if is_augment_sigma_greater else uncond_indicator
723
+ uncond_noise = randn_tensor(latents.shape, generator=generator, device=device, dtype=torch.float32)
724
+ uncond_latent = conditioning_latents + uncond_noise * augment_sigma[:, None, None, None, None]
725
+ uncond_latent = uncond_latent * c_in_augment / c_in_original
726
+ uncond_latent = current_uncond_indicator * uncond_latent + (1 - current_uncond_indicator) * latents
727
+ uncond_latent = self.scheduler.scale_model_input(uncond_latent, t)
728
+ uncond_latent = uncond_latent.to(transformer_dtype)
729
+
730
+ noise_pred_uncond = self.transformer(
731
+ hidden_states=uncond_latent,
732
+ timestep=timestep,
733
+ encoder_hidden_states=negative_prompt_embeds,
734
+ fps=fps,
735
+ condition_mask=uncond_mask,
736
+ padding_mask=padding_mask,
737
+ return_dict=False,
738
+ )[0]
739
+ noise_pred = torch.cat([noise_pred_uncond, noise_pred])
740
+ sample = torch.cat([sample, sample])
741
+
742
+ # pred_original_sample (x0)
743
+ noise_pred = self.scheduler.step(noise_pred, t, sample, return_dict=False)[1]
744
+ self.scheduler._step_index -= 1
745
+
746
+ if self.do_classifier_free_guidance:
747
+ noise_pred_uncond, noise_pred_cond = noise_pred.chunk(2, dim=0)
748
+ noise_pred_uncond = (
749
+ current_uncond_indicator * conditioning_latents
750
+ + (1 - current_uncond_indicator) * noise_pred_uncond
751
+ )
752
+ noise_pred_cond = (
753
+ current_cond_indicator * conditioning_latents + (1 - current_cond_indicator) * noise_pred_cond
754
+ )
755
+ noise_pred = noise_pred_cond + self.guidance_scale * (noise_pred_cond - noise_pred_uncond)
756
+ else:
757
+ noise_pred = (
758
+ current_cond_indicator * conditioning_latents + (1 - current_cond_indicator) * noise_pred
759
+ )
760
+
761
+ # pred_sample (eps)
762
+ latents = self.scheduler.step(
763
+ noise_pred, t, latents, return_dict=False, pred_original_sample=noise_pred
764
+ )[0]
765
+
766
+ if callback_on_step_end is not None:
767
+ callback_kwargs = {}
768
+ for k in callback_on_step_end_tensor_inputs:
769
+ callback_kwargs[k] = locals()[k]
770
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
771
+
772
+ latents = callback_outputs.pop("latents", latents)
773
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
774
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
775
+
776
+ # call the callback, if provided
777
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
778
+ progress_bar.update()
779
+
780
+ if XLA_AVAILABLE:
781
+ xm.mark_step()
782
+
783
+ self._current_timestep = None
784
+
785
+ if not output_type == "latent":
786
+ if self.vae.config.latents_mean is not None:
787
+ latents_mean, latents_std = self.vae.config.latents_mean, self.vae.config.latents_std
788
+ latents_mean = (
789
+ torch.tensor(latents_mean)
790
+ .view(1, self.vae.config.latent_channels, -1, 1, 1)[:, :, : latents.size(2)]
791
+ .to(latents)
792
+ )
793
+ latents_std = (
794
+ torch.tensor(latents_std)
795
+ .view(1, self.vae.config.latent_channels, -1, 1, 1)[:, :, : latents.size(2)]
796
+ .to(latents)
797
+ )
798
+ latents = latents * latents_std / self.scheduler.config.sigma_data + latents_mean
799
+ else:
800
+ latents = latents / self.scheduler.config.sigma_data
801
+ video = self.vae.decode(latents.to(vae_dtype), return_dict=False)[0]
802
+
803
+ if self.safety_checker is not None:
804
+ self.safety_checker.to(device)
805
+ video = self.video_processor.postprocess_video(video, output_type="np")
806
+ video = (video * 255).astype(np.uint8)
807
+ video_batch = []
808
+ for vid in video:
809
+ vid = self.safety_checker.check_video_safety(vid)
810
+ video_batch.append(vid)
811
+ video = np.stack(video_batch).astype(np.float32) / 255.0 * 2 - 1
812
+ video = torch.from_numpy(video).permute(0, 4, 1, 2, 3)
813
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
814
+ self.safety_checker.to("cpu")
815
+ else:
816
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
817
+ else:
818
+ video = latents
819
+
820
+ # Offload all models
821
+ self.maybe_free_model_hooks()
822
+
823
+ if not return_dict:
824
+ return (video,)
825
+
826
+ return CosmosPipelineOutput(frames=video)