diffusers 0.33.1__py3-none-any.whl → 0.35.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 (551) hide show
  1. diffusers/__init__.py +145 -1
  2. diffusers/callbacks.py +35 -0
  3. diffusers/commands/__init__.py +1 -1
  4. diffusers/commands/custom_blocks.py +134 -0
  5. diffusers/commands/diffusers_cli.py +3 -1
  6. diffusers/commands/env.py +1 -1
  7. diffusers/commands/fp16_safetensors.py +2 -2
  8. diffusers/configuration_utils.py +11 -2
  9. diffusers/dependency_versions_check.py +1 -1
  10. diffusers/dependency_versions_table.py +3 -3
  11. diffusers/experimental/rl/value_guided_sampling.py +1 -1
  12. diffusers/guiders/__init__.py +41 -0
  13. diffusers/guiders/adaptive_projected_guidance.py +188 -0
  14. diffusers/guiders/auto_guidance.py +190 -0
  15. diffusers/guiders/classifier_free_guidance.py +141 -0
  16. diffusers/guiders/classifier_free_zero_star_guidance.py +152 -0
  17. diffusers/guiders/frequency_decoupled_guidance.py +327 -0
  18. diffusers/guiders/guider_utils.py +309 -0
  19. diffusers/guiders/perturbed_attention_guidance.py +271 -0
  20. diffusers/guiders/skip_layer_guidance.py +262 -0
  21. diffusers/guiders/smoothed_energy_guidance.py +251 -0
  22. diffusers/guiders/tangential_classifier_free_guidance.py +143 -0
  23. diffusers/hooks/__init__.py +17 -0
  24. diffusers/hooks/_common.py +56 -0
  25. diffusers/hooks/_helpers.py +293 -0
  26. diffusers/hooks/faster_cache.py +9 -8
  27. diffusers/hooks/first_block_cache.py +259 -0
  28. diffusers/hooks/group_offloading.py +332 -227
  29. diffusers/hooks/hooks.py +58 -3
  30. diffusers/hooks/layer_skip.py +263 -0
  31. diffusers/hooks/layerwise_casting.py +5 -10
  32. diffusers/hooks/pyramid_attention_broadcast.py +15 -12
  33. diffusers/hooks/smoothed_energy_guidance_utils.py +167 -0
  34. diffusers/hooks/utils.py +43 -0
  35. diffusers/image_processor.py +7 -2
  36. diffusers/loaders/__init__.py +10 -0
  37. diffusers/loaders/ip_adapter.py +260 -18
  38. diffusers/loaders/lora_base.py +261 -127
  39. diffusers/loaders/lora_conversion_utils.py +657 -35
  40. diffusers/loaders/lora_pipeline.py +2778 -1246
  41. diffusers/loaders/peft.py +78 -112
  42. diffusers/loaders/single_file.py +2 -2
  43. diffusers/loaders/single_file_model.py +64 -15
  44. diffusers/loaders/single_file_utils.py +395 -7
  45. diffusers/loaders/textual_inversion.py +3 -2
  46. diffusers/loaders/transformer_flux.py +10 -11
  47. diffusers/loaders/transformer_sd3.py +8 -3
  48. diffusers/loaders/unet.py +24 -21
  49. diffusers/loaders/unet_loader_utils.py +6 -3
  50. diffusers/loaders/utils.py +1 -1
  51. diffusers/models/__init__.py +23 -1
  52. diffusers/models/activations.py +5 -5
  53. diffusers/models/adapter.py +2 -3
  54. diffusers/models/attention.py +488 -7
  55. diffusers/models/attention_dispatch.py +1218 -0
  56. diffusers/models/attention_flax.py +10 -10
  57. diffusers/models/attention_processor.py +113 -667
  58. diffusers/models/auto_model.py +49 -12
  59. diffusers/models/autoencoders/__init__.py +2 -0
  60. diffusers/models/autoencoders/autoencoder_asym_kl.py +4 -4
  61. diffusers/models/autoencoders/autoencoder_dc.py +17 -4
  62. diffusers/models/autoencoders/autoencoder_kl.py +5 -5
  63. diffusers/models/autoencoders/autoencoder_kl_allegro.py +4 -4
  64. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +6 -6
  65. diffusers/models/autoencoders/autoencoder_kl_cosmos.py +1110 -0
  66. diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py +2 -2
  67. diffusers/models/autoencoders/autoencoder_kl_ltx.py +3 -3
  68. diffusers/models/autoencoders/autoencoder_kl_magvit.py +4 -4
  69. diffusers/models/autoencoders/autoencoder_kl_mochi.py +3 -3
  70. diffusers/models/autoencoders/autoencoder_kl_qwenimage.py +1070 -0
  71. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +4 -4
  72. diffusers/models/autoencoders/autoencoder_kl_wan.py +626 -62
  73. diffusers/models/autoencoders/autoencoder_oobleck.py +1 -1
  74. diffusers/models/autoencoders/autoencoder_tiny.py +3 -3
  75. diffusers/models/autoencoders/consistency_decoder_vae.py +1 -1
  76. diffusers/models/autoencoders/vae.py +13 -2
  77. diffusers/models/autoencoders/vq_model.py +2 -2
  78. diffusers/models/cache_utils.py +32 -10
  79. diffusers/models/controlnet.py +1 -1
  80. diffusers/models/controlnet_flux.py +1 -1
  81. diffusers/models/controlnet_sd3.py +1 -1
  82. diffusers/models/controlnet_sparsectrl.py +1 -1
  83. diffusers/models/controlnets/__init__.py +1 -0
  84. diffusers/models/controlnets/controlnet.py +3 -3
  85. diffusers/models/controlnets/controlnet_flax.py +1 -1
  86. diffusers/models/controlnets/controlnet_flux.py +21 -20
  87. diffusers/models/controlnets/controlnet_hunyuan.py +2 -2
  88. diffusers/models/controlnets/controlnet_sana.py +290 -0
  89. diffusers/models/controlnets/controlnet_sd3.py +1 -1
  90. diffusers/models/controlnets/controlnet_sparsectrl.py +2 -2
  91. diffusers/models/controlnets/controlnet_union.py +5 -5
  92. diffusers/models/controlnets/controlnet_xs.py +7 -7
  93. diffusers/models/controlnets/multicontrolnet.py +4 -5
  94. diffusers/models/controlnets/multicontrolnet_union.py +5 -6
  95. diffusers/models/downsampling.py +2 -2
  96. diffusers/models/embeddings.py +36 -46
  97. diffusers/models/embeddings_flax.py +2 -2
  98. diffusers/models/lora.py +3 -3
  99. diffusers/models/model_loading_utils.py +233 -1
  100. diffusers/models/modeling_flax_utils.py +1 -2
  101. diffusers/models/modeling_utils.py +203 -108
  102. diffusers/models/normalization.py +4 -4
  103. diffusers/models/resnet.py +2 -2
  104. diffusers/models/resnet_flax.py +1 -1
  105. diffusers/models/transformers/__init__.py +7 -0
  106. diffusers/models/transformers/auraflow_transformer_2d.py +70 -24
  107. diffusers/models/transformers/cogvideox_transformer_3d.py +1 -1
  108. diffusers/models/transformers/consisid_transformer_3d.py +1 -1
  109. diffusers/models/transformers/dit_transformer_2d.py +2 -2
  110. diffusers/models/transformers/dual_transformer_2d.py +1 -1
  111. diffusers/models/transformers/hunyuan_transformer_2d.py +2 -2
  112. diffusers/models/transformers/latte_transformer_3d.py +4 -5
  113. diffusers/models/transformers/lumina_nextdit2d.py +2 -2
  114. diffusers/models/transformers/pixart_transformer_2d.py +3 -3
  115. diffusers/models/transformers/prior_transformer.py +1 -1
  116. diffusers/models/transformers/sana_transformer.py +8 -3
  117. diffusers/models/transformers/stable_audio_transformer.py +5 -9
  118. diffusers/models/transformers/t5_film_transformer.py +3 -3
  119. diffusers/models/transformers/transformer_2d.py +1 -1
  120. diffusers/models/transformers/transformer_allegro.py +1 -1
  121. diffusers/models/transformers/transformer_chroma.py +641 -0
  122. diffusers/models/transformers/transformer_cogview3plus.py +5 -10
  123. diffusers/models/transformers/transformer_cogview4.py +353 -27
  124. diffusers/models/transformers/transformer_cosmos.py +586 -0
  125. diffusers/models/transformers/transformer_flux.py +376 -138
  126. diffusers/models/transformers/transformer_hidream_image.py +942 -0
  127. diffusers/models/transformers/transformer_hunyuan_video.py +12 -8
  128. diffusers/models/transformers/transformer_hunyuan_video_framepack.py +416 -0
  129. diffusers/models/transformers/transformer_ltx.py +105 -24
  130. diffusers/models/transformers/transformer_lumina2.py +1 -1
  131. diffusers/models/transformers/transformer_mochi.py +1 -1
  132. diffusers/models/transformers/transformer_omnigen.py +2 -2
  133. diffusers/models/transformers/transformer_qwenimage.py +645 -0
  134. diffusers/models/transformers/transformer_sd3.py +7 -7
  135. diffusers/models/transformers/transformer_skyreels_v2.py +607 -0
  136. diffusers/models/transformers/transformer_temporal.py +1 -1
  137. diffusers/models/transformers/transformer_wan.py +316 -87
  138. diffusers/models/transformers/transformer_wan_vace.py +387 -0
  139. diffusers/models/unets/unet_1d.py +1 -1
  140. diffusers/models/unets/unet_1d_blocks.py +1 -1
  141. diffusers/models/unets/unet_2d.py +1 -1
  142. diffusers/models/unets/unet_2d_blocks.py +1 -1
  143. diffusers/models/unets/unet_2d_blocks_flax.py +8 -7
  144. diffusers/models/unets/unet_2d_condition.py +4 -3
  145. diffusers/models/unets/unet_2d_condition_flax.py +2 -2
  146. diffusers/models/unets/unet_3d_blocks.py +1 -1
  147. diffusers/models/unets/unet_3d_condition.py +3 -3
  148. diffusers/models/unets/unet_i2vgen_xl.py +3 -3
  149. diffusers/models/unets/unet_kandinsky3.py +1 -1
  150. diffusers/models/unets/unet_motion_model.py +2 -2
  151. diffusers/models/unets/unet_stable_cascade.py +1 -1
  152. diffusers/models/upsampling.py +2 -2
  153. diffusers/models/vae_flax.py +2 -2
  154. diffusers/models/vq_model.py +1 -1
  155. diffusers/modular_pipelines/__init__.py +83 -0
  156. diffusers/modular_pipelines/components_manager.py +1068 -0
  157. diffusers/modular_pipelines/flux/__init__.py +66 -0
  158. diffusers/modular_pipelines/flux/before_denoise.py +689 -0
  159. diffusers/modular_pipelines/flux/decoders.py +109 -0
  160. diffusers/modular_pipelines/flux/denoise.py +227 -0
  161. diffusers/modular_pipelines/flux/encoders.py +412 -0
  162. diffusers/modular_pipelines/flux/modular_blocks.py +181 -0
  163. diffusers/modular_pipelines/flux/modular_pipeline.py +59 -0
  164. diffusers/modular_pipelines/modular_pipeline.py +2446 -0
  165. diffusers/modular_pipelines/modular_pipeline_utils.py +672 -0
  166. diffusers/modular_pipelines/node_utils.py +665 -0
  167. diffusers/modular_pipelines/stable_diffusion_xl/__init__.py +77 -0
  168. diffusers/modular_pipelines/stable_diffusion_xl/before_denoise.py +1874 -0
  169. diffusers/modular_pipelines/stable_diffusion_xl/decoders.py +208 -0
  170. diffusers/modular_pipelines/stable_diffusion_xl/denoise.py +771 -0
  171. diffusers/modular_pipelines/stable_diffusion_xl/encoders.py +887 -0
  172. diffusers/modular_pipelines/stable_diffusion_xl/modular_blocks.py +380 -0
  173. diffusers/modular_pipelines/stable_diffusion_xl/modular_pipeline.py +365 -0
  174. diffusers/modular_pipelines/wan/__init__.py +66 -0
  175. diffusers/modular_pipelines/wan/before_denoise.py +365 -0
  176. diffusers/modular_pipelines/wan/decoders.py +105 -0
  177. diffusers/modular_pipelines/wan/denoise.py +261 -0
  178. diffusers/modular_pipelines/wan/encoders.py +242 -0
  179. diffusers/modular_pipelines/wan/modular_blocks.py +144 -0
  180. diffusers/modular_pipelines/wan/modular_pipeline.py +90 -0
  181. diffusers/pipelines/__init__.py +68 -6
  182. diffusers/pipelines/allegro/pipeline_allegro.py +11 -11
  183. diffusers/pipelines/amused/pipeline_amused.py +7 -6
  184. diffusers/pipelines/amused/pipeline_amused_img2img.py +6 -5
  185. diffusers/pipelines/amused/pipeline_amused_inpaint.py +6 -5
  186. diffusers/pipelines/animatediff/pipeline_animatediff.py +6 -6
  187. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +6 -6
  188. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +16 -15
  189. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +6 -6
  190. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +5 -5
  191. diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +5 -5
  192. diffusers/pipelines/audioldm/pipeline_audioldm.py +8 -7
  193. diffusers/pipelines/audioldm2/modeling_audioldm2.py +1 -1
  194. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +22 -13
  195. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +48 -11
  196. diffusers/pipelines/auto_pipeline.py +23 -20
  197. diffusers/pipelines/blip_diffusion/modeling_blip2.py +1 -1
  198. diffusers/pipelines/blip_diffusion/modeling_ctx_clip.py +2 -2
  199. diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +11 -10
  200. diffusers/pipelines/chroma/__init__.py +49 -0
  201. diffusers/pipelines/chroma/pipeline_chroma.py +949 -0
  202. diffusers/pipelines/chroma/pipeline_chroma_img2img.py +1034 -0
  203. diffusers/pipelines/chroma/pipeline_output.py +21 -0
  204. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +17 -16
  205. diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +17 -16
  206. diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +18 -17
  207. diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +17 -16
  208. diffusers/pipelines/cogview3/pipeline_cogview3plus.py +9 -9
  209. diffusers/pipelines/cogview4/pipeline_cogview4.py +23 -22
  210. diffusers/pipelines/cogview4/pipeline_cogview4_control.py +7 -7
  211. diffusers/pipelines/consisid/consisid_utils.py +2 -2
  212. diffusers/pipelines/consisid/pipeline_consisid.py +8 -8
  213. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -1
  214. diffusers/pipelines/controlnet/pipeline_controlnet.py +7 -7
  215. diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +11 -10
  216. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +7 -7
  217. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +7 -7
  218. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +14 -14
  219. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +10 -6
  220. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +13 -13
  221. diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +226 -107
  222. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +12 -8
  223. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +207 -105
  224. diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +1 -1
  225. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +8 -8
  226. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +7 -7
  227. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +7 -7
  228. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +12 -10
  229. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +9 -7
  230. diffusers/pipelines/cosmos/__init__.py +54 -0
  231. diffusers/pipelines/cosmos/pipeline_cosmos2_text2image.py +673 -0
  232. diffusers/pipelines/cosmos/pipeline_cosmos2_video2world.py +792 -0
  233. diffusers/pipelines/cosmos/pipeline_cosmos_text2world.py +664 -0
  234. diffusers/pipelines/cosmos/pipeline_cosmos_video2world.py +826 -0
  235. diffusers/pipelines/cosmos/pipeline_output.py +40 -0
  236. diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +5 -4
  237. diffusers/pipelines/ddim/pipeline_ddim.py +4 -4
  238. diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -1
  239. diffusers/pipelines/deepfloyd_if/pipeline_if.py +10 -10
  240. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +10 -10
  241. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +10 -10
  242. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +10 -10
  243. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +10 -10
  244. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +10 -10
  245. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +8 -8
  246. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +5 -5
  247. diffusers/pipelines/deprecated/audio_diffusion/mel.py +1 -1
  248. diffusers/pipelines/deprecated/audio_diffusion/pipeline_audio_diffusion.py +3 -3
  249. diffusers/pipelines/deprecated/latent_diffusion_uncond/pipeline_latent_diffusion_uncond.py +1 -1
  250. diffusers/pipelines/deprecated/pndm/pipeline_pndm.py +2 -2
  251. diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +4 -3
  252. diffusers/pipelines/deprecated/score_sde_ve/pipeline_score_sde_ve.py +1 -1
  253. diffusers/pipelines/deprecated/spectrogram_diffusion/continuous_encoder.py +1 -1
  254. diffusers/pipelines/deprecated/spectrogram_diffusion/midi_utils.py +1 -1
  255. diffusers/pipelines/deprecated/spectrogram_diffusion/notes_encoder.py +1 -1
  256. diffusers/pipelines/deprecated/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +1 -1
  257. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +8 -8
  258. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_onnx_stable_diffusion_inpaint_legacy.py +9 -9
  259. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +10 -10
  260. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +10 -8
  261. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +5 -5
  262. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +18 -18
  263. diffusers/pipelines/deprecated/stochastic_karras_ve/pipeline_stochastic_karras_ve.py +1 -1
  264. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +2 -2
  265. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py +6 -6
  266. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +5 -5
  267. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +5 -5
  268. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +5 -5
  269. diffusers/pipelines/deprecated/vq_diffusion/pipeline_vq_diffusion.py +1 -1
  270. diffusers/pipelines/dit/pipeline_dit.py +4 -2
  271. diffusers/pipelines/easyanimate/pipeline_easyanimate.py +4 -4
  272. diffusers/pipelines/easyanimate/pipeline_easyanimate_control.py +4 -4
  273. diffusers/pipelines/easyanimate/pipeline_easyanimate_inpaint.py +7 -6
  274. diffusers/pipelines/flux/__init__.py +4 -0
  275. diffusers/pipelines/flux/modeling_flux.py +1 -1
  276. diffusers/pipelines/flux/pipeline_flux.py +37 -36
  277. diffusers/pipelines/flux/pipeline_flux_control.py +9 -9
  278. diffusers/pipelines/flux/pipeline_flux_control_img2img.py +7 -7
  279. diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +7 -7
  280. diffusers/pipelines/flux/pipeline_flux_controlnet.py +7 -7
  281. diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +31 -23
  282. diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +3 -2
  283. diffusers/pipelines/flux/pipeline_flux_fill.py +7 -7
  284. diffusers/pipelines/flux/pipeline_flux_img2img.py +40 -7
  285. diffusers/pipelines/flux/pipeline_flux_inpaint.py +12 -7
  286. diffusers/pipelines/flux/pipeline_flux_kontext.py +1134 -0
  287. diffusers/pipelines/flux/pipeline_flux_kontext_inpaint.py +1460 -0
  288. diffusers/pipelines/flux/pipeline_flux_prior_redux.py +2 -2
  289. diffusers/pipelines/flux/pipeline_output.py +6 -4
  290. diffusers/pipelines/free_init_utils.py +2 -2
  291. diffusers/pipelines/free_noise_utils.py +3 -3
  292. diffusers/pipelines/hidream_image/__init__.py +47 -0
  293. diffusers/pipelines/hidream_image/pipeline_hidream_image.py +1026 -0
  294. diffusers/pipelines/hidream_image/pipeline_output.py +35 -0
  295. diffusers/pipelines/hunyuan_video/__init__.py +2 -0
  296. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_skyreels_image2video.py +8 -8
  297. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +26 -25
  298. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video_framepack.py +1114 -0
  299. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video_image2video.py +71 -15
  300. diffusers/pipelines/hunyuan_video/pipeline_output.py +19 -0
  301. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +8 -8
  302. diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +10 -8
  303. diffusers/pipelines/kandinsky/pipeline_kandinsky.py +6 -6
  304. diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +34 -34
  305. diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +19 -26
  306. diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +7 -7
  307. diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +11 -11
  308. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +6 -6
  309. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +35 -35
  310. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +6 -6
  311. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +17 -39
  312. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +17 -45
  313. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +7 -7
  314. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +10 -10
  315. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +10 -10
  316. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +7 -7
  317. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +17 -38
  318. diffusers/pipelines/kolors/pipeline_kolors.py +10 -10
  319. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +12 -12
  320. diffusers/pipelines/kolors/text_encoder.py +3 -3
  321. diffusers/pipelines/kolors/tokenizer.py +1 -1
  322. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +2 -2
  323. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +2 -2
  324. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -1
  325. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion_superresolution.py +3 -3
  326. diffusers/pipelines/latte/pipeline_latte.py +12 -12
  327. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +13 -13
  328. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +17 -16
  329. diffusers/pipelines/ltx/__init__.py +4 -0
  330. diffusers/pipelines/ltx/modeling_latent_upsampler.py +188 -0
  331. diffusers/pipelines/ltx/pipeline_ltx.py +64 -18
  332. diffusers/pipelines/ltx/pipeline_ltx_condition.py +117 -38
  333. diffusers/pipelines/ltx/pipeline_ltx_image2video.py +63 -18
  334. diffusers/pipelines/ltx/pipeline_ltx_latent_upsample.py +277 -0
  335. diffusers/pipelines/lumina/pipeline_lumina.py +13 -13
  336. diffusers/pipelines/lumina2/pipeline_lumina2.py +10 -10
  337. diffusers/pipelines/marigold/marigold_image_processing.py +2 -2
  338. diffusers/pipelines/mochi/pipeline_mochi.py +15 -14
  339. diffusers/pipelines/musicldm/pipeline_musicldm.py +16 -13
  340. diffusers/pipelines/omnigen/pipeline_omnigen.py +13 -11
  341. diffusers/pipelines/omnigen/processor_omnigen.py +8 -3
  342. diffusers/pipelines/onnx_utils.py +15 -2
  343. diffusers/pipelines/pag/pag_utils.py +2 -2
  344. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +12 -8
  345. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +7 -7
  346. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +10 -6
  347. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +14 -14
  348. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +8 -8
  349. diffusers/pipelines/pag/pipeline_pag_kolors.py +10 -10
  350. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +11 -11
  351. diffusers/pipelines/pag/pipeline_pag_sana.py +18 -12
  352. diffusers/pipelines/pag/pipeline_pag_sd.py +8 -8
  353. diffusers/pipelines/pag/pipeline_pag_sd_3.py +7 -7
  354. diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +7 -7
  355. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +6 -6
  356. diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +5 -5
  357. diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +8 -8
  358. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +16 -15
  359. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +18 -17
  360. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +12 -12
  361. diffusers/pipelines/paint_by_example/image_encoder.py +1 -1
  362. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +8 -7
  363. diffusers/pipelines/pia/pipeline_pia.py +8 -6
  364. diffusers/pipelines/pipeline_flax_utils.py +5 -6
  365. diffusers/pipelines/pipeline_loading_utils.py +113 -15
  366. diffusers/pipelines/pipeline_utils.py +127 -48
  367. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +14 -12
  368. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +31 -11
  369. diffusers/pipelines/qwenimage/__init__.py +55 -0
  370. diffusers/pipelines/qwenimage/pipeline_output.py +21 -0
  371. diffusers/pipelines/qwenimage/pipeline_qwenimage.py +726 -0
  372. diffusers/pipelines/qwenimage/pipeline_qwenimage_edit.py +882 -0
  373. diffusers/pipelines/qwenimage/pipeline_qwenimage_img2img.py +829 -0
  374. diffusers/pipelines/qwenimage/pipeline_qwenimage_inpaint.py +1015 -0
  375. diffusers/pipelines/sana/__init__.py +4 -0
  376. diffusers/pipelines/sana/pipeline_sana.py +23 -21
  377. diffusers/pipelines/sana/pipeline_sana_controlnet.py +1106 -0
  378. diffusers/pipelines/sana/pipeline_sana_sprint.py +23 -19
  379. diffusers/pipelines/sana/pipeline_sana_sprint_img2img.py +981 -0
  380. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +7 -6
  381. diffusers/pipelines/shap_e/camera.py +1 -1
  382. diffusers/pipelines/shap_e/pipeline_shap_e.py +1 -1
  383. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +1 -1
  384. diffusers/pipelines/shap_e/renderer.py +3 -3
  385. diffusers/pipelines/skyreels_v2/__init__.py +59 -0
  386. diffusers/pipelines/skyreels_v2/pipeline_output.py +20 -0
  387. diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2.py +610 -0
  388. diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing.py +978 -0
  389. diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_i2v.py +1059 -0
  390. diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_v2v.py +1063 -0
  391. diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_i2v.py +745 -0
  392. diffusers/pipelines/stable_audio/modeling_stable_audio.py +1 -1
  393. diffusers/pipelines/stable_audio/pipeline_stable_audio.py +5 -5
  394. diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +8 -8
  395. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +13 -13
  396. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +9 -9
  397. diffusers/pipelines/stable_diffusion/__init__.py +0 -7
  398. diffusers/pipelines/stable_diffusion/clip_image_project_model.py +1 -1
  399. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +11 -4
  400. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
  401. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_img2img.py +1 -1
  402. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_inpaint.py +1 -1
  403. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +12 -11
  404. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +10 -10
  405. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +11 -11
  406. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +10 -10
  407. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +10 -9
  408. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +5 -5
  409. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +5 -5
  410. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +5 -5
  411. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +5 -5
  412. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +5 -5
  413. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +4 -4
  414. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +5 -5
  415. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +7 -7
  416. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +5 -5
  417. diffusers/pipelines/stable_diffusion/safety_checker.py +1 -1
  418. diffusers/pipelines/stable_diffusion/safety_checker_flax.py +1 -1
  419. diffusers/pipelines/stable_diffusion/stable_unclip_image_normalizer.py +1 -1
  420. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +13 -12
  421. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +7 -7
  422. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +7 -7
  423. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +12 -8
  424. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +15 -9
  425. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +11 -9
  426. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +11 -9
  427. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +18 -12
  428. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +11 -8
  429. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +11 -8
  430. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +15 -12
  431. diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +8 -6
  432. diffusers/pipelines/stable_diffusion_safe/safety_checker.py +1 -1
  433. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +15 -11
  434. diffusers/pipelines/stable_diffusion_xl/pipeline_flax_stable_diffusion_xl.py +1 -1
  435. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +16 -15
  436. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +18 -17
  437. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +12 -12
  438. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +16 -15
  439. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +3 -3
  440. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +12 -12
  441. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +18 -17
  442. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +12 -7
  443. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +12 -7
  444. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +15 -13
  445. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +24 -21
  446. diffusers/pipelines/unclip/pipeline_unclip.py +4 -3
  447. diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +4 -3
  448. diffusers/pipelines/unclip/text_proj.py +2 -2
  449. diffusers/pipelines/unidiffuser/modeling_text_decoder.py +2 -2
  450. diffusers/pipelines/unidiffuser/modeling_uvit.py +1 -1
  451. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +8 -7
  452. diffusers/pipelines/visualcloze/__init__.py +52 -0
  453. diffusers/pipelines/visualcloze/pipeline_visualcloze_combined.py +444 -0
  454. diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py +952 -0
  455. diffusers/pipelines/visualcloze/visualcloze_utils.py +251 -0
  456. diffusers/pipelines/wan/__init__.py +2 -0
  457. diffusers/pipelines/wan/pipeline_wan.py +91 -30
  458. diffusers/pipelines/wan/pipeline_wan_i2v.py +145 -45
  459. diffusers/pipelines/wan/pipeline_wan_vace.py +975 -0
  460. diffusers/pipelines/wan/pipeline_wan_video2video.py +14 -16
  461. diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +1 -1
  462. diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py +1 -1
  463. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +1 -1
  464. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +8 -8
  465. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +16 -15
  466. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +6 -6
  467. diffusers/quantizers/__init__.py +3 -1
  468. diffusers/quantizers/base.py +17 -1
  469. diffusers/quantizers/bitsandbytes/bnb_quantizer.py +4 -0
  470. diffusers/quantizers/bitsandbytes/utils.py +10 -7
  471. diffusers/quantizers/gguf/gguf_quantizer.py +13 -4
  472. diffusers/quantizers/gguf/utils.py +108 -16
  473. diffusers/quantizers/pipe_quant_config.py +202 -0
  474. diffusers/quantizers/quantization_config.py +18 -16
  475. diffusers/quantizers/quanto/quanto_quantizer.py +4 -0
  476. diffusers/quantizers/torchao/torchao_quantizer.py +31 -1
  477. diffusers/schedulers/__init__.py +3 -1
  478. diffusers/schedulers/deprecated/scheduling_karras_ve.py +4 -3
  479. diffusers/schedulers/deprecated/scheduling_sde_vp.py +1 -1
  480. diffusers/schedulers/scheduling_consistency_models.py +1 -1
  481. diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +10 -5
  482. diffusers/schedulers/scheduling_ddim.py +8 -8
  483. diffusers/schedulers/scheduling_ddim_cogvideox.py +5 -5
  484. diffusers/schedulers/scheduling_ddim_flax.py +6 -6
  485. diffusers/schedulers/scheduling_ddim_inverse.py +6 -6
  486. diffusers/schedulers/scheduling_ddim_parallel.py +22 -22
  487. diffusers/schedulers/scheduling_ddpm.py +9 -9
  488. diffusers/schedulers/scheduling_ddpm_flax.py +7 -7
  489. diffusers/schedulers/scheduling_ddpm_parallel.py +18 -18
  490. diffusers/schedulers/scheduling_ddpm_wuerstchen.py +2 -2
  491. diffusers/schedulers/scheduling_deis_multistep.py +16 -9
  492. diffusers/schedulers/scheduling_dpm_cogvideox.py +5 -5
  493. diffusers/schedulers/scheduling_dpmsolver_multistep.py +18 -12
  494. diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py +22 -20
  495. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +11 -11
  496. diffusers/schedulers/scheduling_dpmsolver_sde.py +2 -2
  497. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +19 -13
  498. diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +13 -8
  499. diffusers/schedulers/scheduling_edm_euler.py +20 -11
  500. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +3 -3
  501. diffusers/schedulers/scheduling_euler_discrete.py +3 -3
  502. diffusers/schedulers/scheduling_euler_discrete_flax.py +3 -3
  503. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +20 -5
  504. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +1 -1
  505. diffusers/schedulers/scheduling_flow_match_lcm.py +561 -0
  506. diffusers/schedulers/scheduling_heun_discrete.py +2 -2
  507. diffusers/schedulers/scheduling_ipndm.py +2 -2
  508. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +2 -2
  509. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +2 -2
  510. diffusers/schedulers/scheduling_karras_ve_flax.py +5 -5
  511. diffusers/schedulers/scheduling_lcm.py +3 -3
  512. diffusers/schedulers/scheduling_lms_discrete.py +2 -2
  513. diffusers/schedulers/scheduling_lms_discrete_flax.py +1 -1
  514. diffusers/schedulers/scheduling_pndm.py +4 -4
  515. diffusers/schedulers/scheduling_pndm_flax.py +4 -4
  516. diffusers/schedulers/scheduling_repaint.py +9 -9
  517. diffusers/schedulers/scheduling_sasolver.py +15 -15
  518. diffusers/schedulers/scheduling_scm.py +1 -2
  519. diffusers/schedulers/scheduling_sde_ve.py +1 -1
  520. diffusers/schedulers/scheduling_sde_ve_flax.py +2 -2
  521. diffusers/schedulers/scheduling_tcd.py +3 -3
  522. diffusers/schedulers/scheduling_unclip.py +5 -5
  523. diffusers/schedulers/scheduling_unipc_multistep.py +21 -12
  524. diffusers/schedulers/scheduling_utils.py +3 -3
  525. diffusers/schedulers/scheduling_utils_flax.py +2 -2
  526. diffusers/schedulers/scheduling_vq_diffusion.py +1 -1
  527. diffusers/training_utils.py +91 -5
  528. diffusers/utils/__init__.py +15 -0
  529. diffusers/utils/accelerate_utils.py +1 -1
  530. diffusers/utils/constants.py +4 -0
  531. diffusers/utils/doc_utils.py +1 -1
  532. diffusers/utils/dummy_pt_objects.py +432 -0
  533. diffusers/utils/dummy_torch_and_transformers_objects.py +480 -0
  534. diffusers/utils/dynamic_modules_utils.py +85 -8
  535. diffusers/utils/export_utils.py +1 -1
  536. diffusers/utils/hub_utils.py +33 -17
  537. diffusers/utils/import_utils.py +151 -18
  538. diffusers/utils/logging.py +1 -1
  539. diffusers/utils/outputs.py +2 -1
  540. diffusers/utils/peft_utils.py +96 -10
  541. diffusers/utils/state_dict_utils.py +20 -3
  542. diffusers/utils/testing_utils.py +195 -17
  543. diffusers/utils/torch_utils.py +43 -5
  544. diffusers/video_processor.py +2 -2
  545. {diffusers-0.33.1.dist-info → diffusers-0.35.0.dist-info}/METADATA +72 -57
  546. diffusers-0.35.0.dist-info/RECORD +703 -0
  547. {diffusers-0.33.1.dist-info → diffusers-0.35.0.dist-info}/WHEEL +1 -1
  548. diffusers-0.33.1.dist-info/RECORD +0 -608
  549. {diffusers-0.33.1.dist-info → diffusers-0.35.0.dist-info}/LICENSE +0 -0
  550. {diffusers-0.33.1.dist-info → diffusers-0.35.0.dist-info}/entry_points.txt +0 -0
  551. {diffusers-0.33.1.dist-info → diffusers-0.35.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1110 @@
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 math
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+
22
+ from ...configuration_utils import ConfigMixin, register_to_config
23
+ from ...utils import get_logger
24
+ from ...utils.accelerate_utils import apply_forward_hook
25
+ from ..modeling_outputs import AutoencoderKLOutput
26
+ from ..modeling_utils import ModelMixin
27
+ from .vae import DecoderOutput, IdentityDistribution
28
+
29
+
30
+ logger = get_logger(__name__)
31
+
32
+
33
+ # fmt: off
34
+ # These latents and means are from CV8x8x8-1.0. Each checkpoint has different values, but since this is the main VAE used,
35
+ # we will default to these values.
36
+ LATENTS_MEAN = [0.11362758, -0.0171717, 0.03071163, 0.02046862, 0.01931456, 0.02138567, 0.01999342, 0.02189187, 0.02011935, 0.01872694, 0.02168613, 0.02207148, 0.01986941, 0.01770413, 0.02067643, 0.02028245, 0.19125476, 0.04556972, 0.0595558, 0.05315534, 0.05496629, 0.05356264, 0.04856596, 0.05327453, 0.05410472, 0.05597149, 0.05524866, 0.05181874, 0.05071663, 0.05204537, 0.0564108, 0.05518042, 0.01306714, 0.03341161, 0.03847246, 0.02810185, 0.02790166, 0.02920026, 0.02823597, 0.02631033, 0.0278531, 0.02880507, 0.02977769, 0.03145441, 0.02888389, 0.03280773, 0.03484927, 0.03049198, -0.00197727, 0.07534957, 0.04963879, 0.05530893, 0.05410828, 0.05252541, 0.05029899, 0.05321025, 0.05149245, 0.0511921, 0.04643495, 0.04604527, 0.04631618, 0.04404101, 0.04403536, 0.04499495, -0.02994183, -0.04787003, -0.01064558, -0.01779824, -0.01490502, -0.02157517, -0.0204778, -0.02180816, -0.01945375, -0.02062863, -0.02192209, -0.02520639, -0.02246656, -0.02427533, -0.02683363, -0.02762006, 0.08019473, -0.13005368, -0.07568636, -0.06082374, -0.06036175, -0.05875364, -0.05921887, -0.05869788, -0.05273941, -0.052565, -0.05346428, -0.05456541, -0.053657, -0.05656897, -0.05728589, -0.05321847, 0.16718403, -0.00390146, 0.0379406, 0.0356561, 0.03554131, 0.03924074, 0.03873615, 0.04187329, 0.04226924, 0.04378717, 0.04684274, 0.05117614, 0.04547792, 0.05251586, 0.05048339, 0.04950784, 0.09564418, 0.0547128, 0.08183969, 0.07978633, 0.08076023, 0.08108605, 0.08011818, 0.07965573, 0.08187773, 0.08350263, 0.08101469, 0.0786941, 0.0774442, 0.07724521, 0.07830418, 0.07599796, -0.04987567, 0.05923908, -0.01058746, -0.01177603, -0.01116162, -0.01364149, -0.01546014, -0.0117213, -0.01780043, -0.01648314, -0.02100247, -0.02104417, -0.02482123, -0.02611689, -0.02561143, -0.02597336, -0.05364667, 0.08211684, 0.04686937, 0.04605641, 0.04304186, 0.0397355, 0.03686767, 0.04087112, 0.03704741, 0.03706401, 0.03120073, 0.03349091, 0.03319963, 0.03205781, 0.03195127, 0.03180481, 0.16427967, -0.11048453, -0.04595276, -0.04982893, -0.05213465, -0.04809378, -0.05080318, -0.04992863, -0.04493337, -0.0467619, -0.04884703, -0.04627892, -0.04913311, -0.04955709, -0.04533982, -0.04570218, -0.10612928, -0.05121198, -0.06761009, -0.07251801, -0.07265285, -0.07417855, -0.07202412, -0.07499027, -0.07625481, -0.07535747, -0.07638787, -0.07920305, -0.07596069, -0.07959418, -0.08265036, -0.07955471, -0.16888915, 0.0753242, 0.04062594, 0.03375093, 0.03337452, 0.03699376, 0.03651138, 0.03611023, 0.03555622, 0.03378554, 0.0300498, 0.03395559, 0.02941847, 0.03156432, 0.03431173, 0.03016853, -0.03415358, -0.01699573, -0.04029295, -0.04912157, -0.0498858, -0.04917918, -0.04918056, -0.0525189, -0.05325506, -0.05341973, -0.04983329, -0.04883146, -0.04985548, -0.04736718, -0.0462027, -0.04836091, 0.02055675, 0.03419799, -0.02907669, -0.04350509, -0.04156144, -0.04234421, -0.04446109, -0.04461774, -0.04882839, -0.04822346, -0.04502493, -0.0506244, -0.05146913, -0.04655267, -0.04862994, -0.04841615, 0.20312774, -0.07208502, -0.03635615, -0.03556088, -0.04246174, -0.04195838, -0.04293778, -0.04071276, -0.04240569, -0.04125213, -0.04395144, -0.03959096, -0.04044993, -0.04015875, -0.04088107, -0.03885176]
37
+ LATENTS_STD = [0.56700271, 0.65488982, 0.65589428, 0.66524369, 0.66619784, 0.6666382, 0.6720838, 0.66955978, 0.66928875, 0.67108786, 0.67092526, 0.67397463, 0.67894882, 0.67668313, 0.67769569, 0.67479557, 0.85245121, 0.8688373, 0.87348086, 0.88459337, 0.89135885, 0.8910504, 0.89714909, 0.89947474, 0.90201765, 0.90411824, 0.90692616, 0.90847772, 0.90648711, 0.91006982, 0.91033435, 0.90541548, 0.84960359, 0.85863352, 0.86895317, 0.88460612, 0.89245003, 0.89451706, 0.89931005, 0.90647358, 0.90338236, 0.90510076, 0.91008312, 0.90961218, 0.9123717, 0.91313171, 0.91435546, 0.91565102, 0.91877103, 0.85155135, 0.857804, 0.86998034, 0.87365264, 0.88161767, 0.88151032, 0.88758916, 0.89015514, 0.89245576, 0.89276224, 0.89450496, 0.90054202, 0.89994133, 0.90136105, 0.90114892, 0.77755755, 0.81456852, 0.81911844, 0.83137071, 0.83820474, 0.83890373, 0.84401101, 0.84425181, 0.84739357, 0.84798753, 0.85249585, 0.85114998, 0.85160935, 0.85626358, 0.85677862, 0.85641026, 0.69903517, 0.71697885, 0.71696913, 0.72583169, 0.72931731, 0.73254126, 0.73586977, 0.73734969, 0.73664582, 0.74084908, 0.74399322, 0.74471819, 0.74493188, 0.74824578, 0.75024873, 0.75274801, 0.8187142, 0.82251883, 0.82616025, 0.83164483, 0.84072375, 0.8396467, 0.84143305, 0.84880769, 0.8503468, 0.85196948, 0.85211051, 0.85386664, 0.85410017, 0.85439342, 0.85847849, 0.85385275, 0.67583984, 0.68259847, 0.69198853, 0.69928843, 0.70194328, 0.70467001, 0.70755547, 0.70917857, 0.71007699, 0.70963502, 0.71064079, 0.71027333, 0.71291167, 0.71537536, 0.71902508, 0.71604162, 0.72450989, 0.71979928, 0.72057378, 0.73035461, 0.73329622, 0.73660028, 0.73891461, 0.74279994, 0.74105692, 0.74002433, 0.74257588, 0.74416119, 0.74543899, 0.74694443, 0.74747062, 0.74586403, 0.90176988, 0.90990674, 0.91106802, 0.92163783, 0.92390233, 0.93056196, 0.93482202, 0.93642414, 0.93858379, 0.94064975, 0.94078934, 0.94325715, 0.94955301, 0.94814706, 0.95144123, 0.94923073, 0.49853548, 0.64968109, 0.6427654, 0.64966393, 0.6487664, 0.65203559, 0.6584242, 0.65351611, 0.65464371, 0.6574859, 0.65626335, 0.66123748, 0.66121179, 0.66077942, 0.66040152, 0.66474909, 0.61986589, 0.69138134, 0.6884557, 0.6955843, 0.69765401, 0.70015347, 0.70529598, 0.70468754, 0.70399523, 0.70479989, 0.70887572, 0.71126866, 0.7097227, 0.71249932, 0.71231949, 0.71175605, 0.35586974, 0.68723857, 0.68973219, 0.69958478, 0.6943453, 0.6995818, 0.70980215, 0.69899458, 0.70271689, 0.70095056, 0.69912851, 0.70522696, 0.70392174, 0.70916915, 0.70585734, 0.70373541, 0.98101336, 0.89024764, 0.89607251, 0.90678179, 0.91308665, 0.91812348, 0.91980827, 0.92480654, 0.92635667, 0.92887944, 0.93338072, 0.93468094, 0.93619436, 0.93906063, 0.94191772, 0.94471723, 0.83202779, 0.84106231, 0.84463632, 0.85829508, 0.86319661, 0.86751342, 0.86914337, 0.87085921, 0.87286359, 0.87537396, 0.87931138, 0.88054478, 0.8811838, 0.88872558, 0.88942474, 0.88934827, 0.44025335, 0.63061613, 0.63110614, 0.63601959, 0.6395812, 0.64104342, 0.65019929, 0.6502797, 0.64355946, 0.64657205, 0.64847094, 0.64728117, 0.64972943, 0.65162975, 0.65328044, 0.64914775]
38
+ _WAVELETS = {
39
+ "haar": torch.tensor([0.7071067811865476, 0.7071067811865476]),
40
+ "rearrange": torch.tensor([1.0, 1.0]),
41
+ }
42
+ # fmt: on
43
+
44
+
45
+ class CosmosCausalConv3d(nn.Conv3d):
46
+ def __init__(
47
+ self,
48
+ in_channels: int = 1,
49
+ out_channels: int = 1,
50
+ kernel_size: Union[int, Tuple[int, int, int]] = (3, 3, 3),
51
+ dilation: Union[int, Tuple[int, int, int]] = (1, 1, 1),
52
+ stride: Union[int, Tuple[int, int, int]] = (1, 1, 1),
53
+ padding: int = 1,
54
+ pad_mode: str = "constant",
55
+ ) -> None:
56
+ kernel_size = (kernel_size, kernel_size, kernel_size) if isinstance(kernel_size, int) else kernel_size
57
+ dilation = (dilation, dilation, dilation) if isinstance(dilation, int) else dilation
58
+ stride = (stride, stride, stride) if isinstance(stride, int) else stride
59
+
60
+ _, height_kernel_size, width_kernel_size = kernel_size
61
+ assert height_kernel_size % 2 == 1 and width_kernel_size % 2 == 1
62
+
63
+ super().__init__(
64
+ in_channels,
65
+ out_channels,
66
+ kernel_size,
67
+ stride=stride,
68
+ dilation=dilation,
69
+ )
70
+
71
+ self.pad_mode = pad_mode
72
+ self.temporal_pad = dilation[0] * (kernel_size[0] - 1) + (1 - stride[0])
73
+ self.spatial_pad = (padding, padding, padding, padding)
74
+
75
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
76
+ hidden_states_prev = hidden_states[:, :, :1, ...].repeat(1, 1, self.temporal_pad, 1, 1)
77
+ hidden_states = torch.cat([hidden_states_prev, hidden_states], dim=2)
78
+ hidden_states = F.pad(hidden_states, (*self.spatial_pad, 0, 0), mode=self.pad_mode, value=0.0)
79
+ return super().forward(hidden_states)
80
+
81
+
82
+ class CosmosCausalGroupNorm(torch.nn.Module):
83
+ def __init__(self, in_channels: int, num_groups: int = 1):
84
+ super().__init__()
85
+ self.norm = nn.GroupNorm(
86
+ num_groups=num_groups,
87
+ num_channels=in_channels,
88
+ eps=1e-6,
89
+ affine=True,
90
+ )
91
+ self.num_groups = num_groups
92
+
93
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
94
+ if self.num_groups == 1:
95
+ batch_size = hidden_states.size(0)
96
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4).flatten(0, 1) # [B, C, T, H, W] -> [B * T, C, H, W]
97
+ hidden_states = self.norm(hidden_states)
98
+ hidden_states = hidden_states.unflatten(0, (batch_size, -1)).permute(
99
+ 0, 2, 1, 3, 4
100
+ ) # [B * T, C, H, W] -> [B, C, T, H, W]
101
+ else:
102
+ hidden_states = self.norm(hidden_states)
103
+ return hidden_states
104
+
105
+
106
+ class CosmosPatchEmbed3d(nn.Module):
107
+ def __init__(self, patch_size: int = 1, patch_method: str = "haar") -> None:
108
+ super().__init__()
109
+
110
+ self.patch_size = patch_size
111
+ self.patch_method = patch_method
112
+
113
+ wavelets = _WAVELETS.get(patch_method).clone()
114
+ arange = torch.arange(wavelets.shape[0])
115
+
116
+ self.register_buffer("wavelets", wavelets, persistent=False)
117
+ self.register_buffer("_arange", arange, persistent=False)
118
+
119
+ def _dwt(self, hidden_states: torch.Tensor, mode: str = "reflect", rescale=False) -> torch.Tensor:
120
+ dtype = hidden_states.dtype
121
+ wavelets = self.wavelets
122
+
123
+ n = wavelets.shape[0]
124
+ g = hidden_states.shape[1]
125
+ hl = wavelets.flip(0).reshape(1, 1, -1).repeat(g, 1, 1)
126
+ hh = (wavelets * ((-1) ** self._arange)).reshape(1, 1, -1).repeat(g, 1, 1)
127
+ hh = hh.to(dtype=dtype)
128
+ hl = hl.to(dtype=dtype)
129
+
130
+ # Handles temporal axis
131
+ hidden_states = F.pad(hidden_states, pad=(max(0, n - 2), n - 1, n - 2, n - 1, n - 2, n - 1), mode=mode).to(
132
+ dtype
133
+ )
134
+ xl = F.conv3d(hidden_states, hl.unsqueeze(3).unsqueeze(4), groups=g, stride=(2, 1, 1))
135
+ xh = F.conv3d(hidden_states, hh.unsqueeze(3).unsqueeze(4), groups=g, stride=(2, 1, 1))
136
+
137
+ # Handles spatial axes
138
+ xll = F.conv3d(xl, hl.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1))
139
+ xlh = F.conv3d(xl, hh.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1))
140
+ xhl = F.conv3d(xh, hl.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1))
141
+ xhh = F.conv3d(xh, hh.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1))
142
+
143
+ xlll = F.conv3d(xll, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
144
+ xllh = F.conv3d(xll, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
145
+ xlhl = F.conv3d(xlh, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
146
+ xlhh = F.conv3d(xlh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
147
+ xhll = F.conv3d(xhl, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
148
+ xhlh = F.conv3d(xhl, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
149
+ xhhl = F.conv3d(xhh, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
150
+ xhhh = F.conv3d(xhh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
151
+
152
+ hidden_states = torch.cat([xlll, xllh, xlhl, xlhh, xhll, xhlh, xhhl, xhhh], dim=1)
153
+ if rescale:
154
+ hidden_states = hidden_states / 8**0.5
155
+ return hidden_states
156
+
157
+ def _haar(self, hidden_states: torch.Tensor) -> torch.Tensor:
158
+ xi, xv = torch.split(hidden_states, [1, hidden_states.shape[2] - 1], dim=2)
159
+ hidden_states = torch.cat([xi.repeat_interleave(self.patch_size, dim=2), xv], dim=2)
160
+ for _ in range(int(math.log2(self.patch_size))):
161
+ hidden_states = self._dwt(hidden_states, rescale=True)
162
+ return hidden_states
163
+
164
+ def _arrange(self, hidden_states: torch.Tensor) -> torch.Tensor:
165
+ xi, xv = torch.split(hidden_states, [1, hidden_states.shape[2] - 1], dim=2)
166
+ hidden_states = torch.cat([xi.repeat_interleave(self.patch_size, dim=2), xv], dim=2)
167
+
168
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
169
+ p = self.patch_size
170
+
171
+ hidden_states = hidden_states.reshape(
172
+ batch_size, num_channels, num_frames // p, p, height // p, p, width // p, p
173
+ )
174
+ hidden_states = hidden_states.permute(0, 1, 3, 5, 7, 2, 4, 6).flatten(1, 4).contiguous()
175
+ return hidden_states
176
+
177
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
178
+ if self.patch_method == "haar":
179
+ return self._haar(hidden_states)
180
+ elif self.patch_method == "rearrange":
181
+ return self._arrange(hidden_states)
182
+ else:
183
+ raise ValueError(f"Unsupported patch method: {self.patch_method}")
184
+
185
+
186
+ class CosmosUnpatcher3d(nn.Module):
187
+ def __init__(self, patch_size: int = 1, patch_method: str = "haar"):
188
+ super().__init__()
189
+
190
+ self.patch_size = patch_size
191
+ self.patch_method = patch_method
192
+
193
+ wavelets = _WAVELETS.get(patch_method).clone()
194
+ arange = torch.arange(wavelets.shape[0])
195
+
196
+ self.register_buffer("wavelets", wavelets, persistent=False)
197
+ self.register_buffer("_arange", arange, persistent=False)
198
+
199
+ def _idwt(self, hidden_states: torch.Tensor, rescale: bool = False) -> torch.Tensor:
200
+ device = hidden_states.device
201
+ dtype = hidden_states.dtype
202
+ h = self.wavelets.to(device)
203
+
204
+ g = hidden_states.shape[1] // 8 # split into 8 spatio-temporal filtered tesnors.
205
+ hl = h.flip([0]).reshape(1, 1, -1).repeat([g, 1, 1])
206
+ hh = (h * ((-1) ** self._arange.to(device))).reshape(1, 1, -1).repeat(g, 1, 1)
207
+ hl = hl.to(dtype=dtype)
208
+ hh = hh.to(dtype=dtype)
209
+
210
+ xlll, xllh, xlhl, xlhh, xhll, xhlh, xhhl, xhhh = torch.chunk(hidden_states, 8, dim=1)
211
+
212
+ # Handle height transposed convolutions
213
+ xll = F.conv_transpose3d(xlll, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
214
+ xll = F.conv_transpose3d(xllh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xll
215
+
216
+ xlh = F.conv_transpose3d(xlhl, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
217
+ xlh = F.conv_transpose3d(xlhh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xlh
218
+
219
+ xhl = F.conv_transpose3d(xhll, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
220
+ xhl = F.conv_transpose3d(xhlh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xhl
221
+
222
+ xhh = F.conv_transpose3d(xhhl, hl.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2))
223
+ xhh = F.conv_transpose3d(xhhh, hh.unsqueeze(2).unsqueeze(3), groups=g, stride=(1, 1, 2)) + xhh
224
+
225
+ # Handles width transposed convolutions
226
+ xl = F.conv_transpose3d(xll, hl.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1))
227
+ xl = F.conv_transpose3d(xlh, hh.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1)) + xl
228
+ xh = F.conv_transpose3d(xhl, hl.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1))
229
+ xh = F.conv_transpose3d(xhh, hh.unsqueeze(2).unsqueeze(4), groups=g, stride=(1, 2, 1)) + xh
230
+
231
+ # Handles time axis transposed convolutions
232
+ hidden_states = F.conv_transpose3d(xl, hl.unsqueeze(3).unsqueeze(4), groups=g, stride=(2, 1, 1))
233
+ hidden_states = (
234
+ F.conv_transpose3d(xh, hh.unsqueeze(3).unsqueeze(4), groups=g, stride=(2, 1, 1)) + hidden_states
235
+ )
236
+
237
+ if rescale:
238
+ hidden_states = hidden_states * 8**0.5
239
+
240
+ return hidden_states
241
+
242
+ def _ihaar(self, hidden_states: torch.Tensor) -> torch.Tensor:
243
+ for _ in range(int(math.log2(self.patch_size))):
244
+ hidden_states = self._idwt(hidden_states, rescale=True)
245
+ hidden_states = hidden_states[:, :, self.patch_size - 1 :, ...]
246
+ return hidden_states
247
+
248
+ def _irearrange(self, hidden_states: torch.Tensor) -> torch.Tensor:
249
+ p = self.patch_size
250
+ hidden_states = hidden_states.unflatten(1, (-1, p, p, p))
251
+ hidden_states = hidden_states.permute(0, 1, 5, 2, 6, 3, 7, 4)
252
+ hidden_states = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
253
+ hidden_states = hidden_states[:, :, p - 1 :, ...]
254
+ return hidden_states
255
+
256
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
257
+ if self.patch_method == "haar":
258
+ return self._ihaar(hidden_states)
259
+ elif self.patch_method == "rearrange":
260
+ return self._irearrange(hidden_states)
261
+ else:
262
+ raise ValueError("Unknown patch method: " + self.patch_method)
263
+
264
+
265
+ class CosmosConvProjection3d(nn.Module):
266
+ def __init__(self, in_channels: int, out_channels: int) -> None:
267
+ super().__init__()
268
+
269
+ self.conv_s = CosmosCausalConv3d(in_channels, out_channels, kernel_size=(1, 3, 3), stride=1, padding=1)
270
+ self.conv_t = CosmosCausalConv3d(out_channels, out_channels, kernel_size=(3, 1, 1), stride=1, padding=0)
271
+
272
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
273
+ hidden_states = self.conv_s(hidden_states)
274
+ hidden_states = self.conv_t(hidden_states)
275
+ return hidden_states
276
+
277
+
278
+ class CosmosResnetBlock3d(nn.Module):
279
+ def __init__(
280
+ self,
281
+ in_channels: int,
282
+ out_channels: int,
283
+ dropout: float = 0.0,
284
+ num_groups: int = 1,
285
+ ) -> None:
286
+ super().__init__()
287
+ out_channels = out_channels or in_channels
288
+
289
+ self.norm1 = CosmosCausalGroupNorm(in_channels, num_groups)
290
+ self.conv1 = CosmosConvProjection3d(in_channels, out_channels)
291
+
292
+ self.norm2 = CosmosCausalGroupNorm(out_channels, num_groups)
293
+ self.dropout = nn.Dropout(dropout)
294
+ self.conv2 = CosmosConvProjection3d(out_channels, out_channels)
295
+
296
+ if in_channels != out_channels:
297
+ self.conv_shortcut = CosmosCausalConv3d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
298
+ else:
299
+ self.conv_shortcut = nn.Identity()
300
+
301
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
302
+ residual = hidden_states
303
+ residual = self.conv_shortcut(residual)
304
+
305
+ hidden_states = self.norm1(hidden_states)
306
+ hidden_states = F.silu(hidden_states)
307
+ hidden_states = self.conv1(hidden_states)
308
+
309
+ hidden_states = self.norm2(hidden_states)
310
+ hidden_states = F.silu(hidden_states)
311
+ hidden_states = self.dropout(hidden_states)
312
+ hidden_states = self.conv2(hidden_states)
313
+
314
+ return hidden_states + residual
315
+
316
+
317
+ class CosmosDownsample3d(nn.Module):
318
+ def __init__(
319
+ self,
320
+ in_channels: int,
321
+ spatial_downsample: bool = True,
322
+ temporal_downsample: bool = True,
323
+ ) -> None:
324
+ super().__init__()
325
+
326
+ self.spatial_downsample = spatial_downsample
327
+ self.temporal_downsample = temporal_downsample
328
+
329
+ self.conv1 = nn.Identity()
330
+ self.conv2 = nn.Identity()
331
+ self.conv3 = nn.Identity()
332
+
333
+ if spatial_downsample:
334
+ self.conv1 = CosmosCausalConv3d(
335
+ in_channels, in_channels, kernel_size=(1, 3, 3), stride=(1, 2, 2), padding=0
336
+ )
337
+ if temporal_downsample:
338
+ self.conv2 = CosmosCausalConv3d(
339
+ in_channels, in_channels, kernel_size=(3, 1, 1), stride=(2, 1, 1), padding=0
340
+ )
341
+ if spatial_downsample or temporal_downsample:
342
+ self.conv3 = CosmosCausalConv3d(
343
+ in_channels, in_channels, kernel_size=(1, 1, 1), stride=(1, 1, 1), padding=0
344
+ )
345
+
346
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
347
+ if not self.spatial_downsample and not self.temporal_downsample:
348
+ return hidden_states
349
+
350
+ if self.spatial_downsample:
351
+ pad = (0, 1, 0, 1, 0, 0)
352
+ hidden_states = F.pad(hidden_states, pad, mode="constant", value=0)
353
+ conv_out = self.conv1(hidden_states)
354
+ pool_out = F.avg_pool3d(hidden_states, kernel_size=(1, 2, 2), stride=(1, 2, 2))
355
+ hidden_states = conv_out + pool_out
356
+
357
+ if self.temporal_downsample:
358
+ hidden_states = torch.cat([hidden_states[:, :, :1, ...], hidden_states], dim=2)
359
+ conv_out = self.conv2(hidden_states)
360
+ pool_out = F.avg_pool3d(hidden_states, kernel_size=(2, 1, 1), stride=(2, 1, 1))
361
+ hidden_states = conv_out + pool_out
362
+
363
+ hidden_states = self.conv3(hidden_states)
364
+ return hidden_states
365
+
366
+
367
+ class CosmosUpsample3d(nn.Module):
368
+ def __init__(
369
+ self,
370
+ in_channels: int,
371
+ spatial_upsample: bool = True,
372
+ temporal_upsample: bool = True,
373
+ ) -> None:
374
+ super().__init__()
375
+
376
+ self.spatial_upsample = spatial_upsample
377
+ self.temporal_upsample = temporal_upsample
378
+
379
+ self.conv1 = nn.Identity()
380
+ self.conv2 = nn.Identity()
381
+ self.conv3 = nn.Identity()
382
+
383
+ if temporal_upsample:
384
+ self.conv1 = CosmosCausalConv3d(
385
+ in_channels, in_channels, kernel_size=(3, 1, 1), stride=(1, 1, 1), padding=0
386
+ )
387
+ if spatial_upsample:
388
+ self.conv2 = CosmosCausalConv3d(
389
+ in_channels, in_channels, kernel_size=(1, 3, 3), stride=(1, 1, 1), padding=1
390
+ )
391
+ if spatial_upsample or temporal_upsample:
392
+ self.conv3 = CosmosCausalConv3d(
393
+ in_channels, in_channels, kernel_size=(1, 1, 1), stride=(1, 1, 1), padding=0
394
+ )
395
+
396
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
397
+ if not self.spatial_upsample and not self.temporal_upsample:
398
+ return hidden_states
399
+
400
+ if self.temporal_upsample:
401
+ num_frames = hidden_states.size(2)
402
+ time_factor = int(1.0 + 1.0 * (num_frames > 1))
403
+ hidden_states = hidden_states.repeat_interleave(int(time_factor), dim=2)
404
+ hidden_states = hidden_states[..., time_factor - 1 :, :, :]
405
+ hidden_states = self.conv1(hidden_states) + hidden_states
406
+
407
+ if self.spatial_upsample:
408
+ hidden_states = hidden_states.repeat_interleave(2, dim=3).repeat_interleave(2, dim=4)
409
+ hidden_states = self.conv2(hidden_states) + hidden_states
410
+
411
+ hidden_states = self.conv3(hidden_states)
412
+ return hidden_states
413
+
414
+
415
+ class CosmosCausalAttention(nn.Module):
416
+ def __init__(
417
+ self,
418
+ num_attention_heads: int,
419
+ attention_head_dim: int,
420
+ num_groups: int = 1,
421
+ dropout: float = 0.0,
422
+ processor: Union["CosmosSpatialAttentionProcessor2_0", "CosmosTemporalAttentionProcessor2_0"] = None,
423
+ ) -> None:
424
+ super().__init__()
425
+ self.num_attention_heads = num_attention_heads
426
+
427
+ self.norm = CosmosCausalGroupNorm(attention_head_dim, num_groups=num_groups)
428
+ self.to_q = CosmosCausalConv3d(attention_head_dim, attention_head_dim, kernel_size=1, stride=1, padding=0)
429
+ self.to_k = CosmosCausalConv3d(attention_head_dim, attention_head_dim, kernel_size=1, stride=1, padding=0)
430
+ self.to_v = CosmosCausalConv3d(attention_head_dim, attention_head_dim, kernel_size=1, stride=1, padding=0)
431
+ self.to_out = nn.ModuleList([])
432
+ self.to_out.append(
433
+ CosmosCausalConv3d(attention_head_dim, attention_head_dim, kernel_size=1, stride=1, padding=0)
434
+ )
435
+ self.to_out.append(nn.Dropout(dropout))
436
+
437
+ self.processor = processor
438
+ if self.processor is None:
439
+ raise ValueError("CosmosCausalAttention requires a processor.")
440
+
441
+ def forward(self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
442
+ return self.processor(self, hidden_states=hidden_states, attention_mask=attention_mask)
443
+
444
+
445
+ class CosmosSpatialAttentionProcessor2_0:
446
+ def __init__(self):
447
+ if not hasattr(F, "scaled_dot_product_attention"):
448
+ raise ImportError(
449
+ "CosmosSpatialAttentionProcessor2_0 requires PyTorch 2.0 or higher. To use it, please upgrade PyTorch."
450
+ )
451
+
452
+ def __call__(
453
+ self, attn: CosmosCausalAttention, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None
454
+ ) -> torch.Tensor:
455
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
456
+ residual = hidden_states
457
+
458
+ hidden_states = attn.norm(hidden_states)
459
+ query = attn.to_q(hidden_states)
460
+ key = attn.to_k(hidden_states)
461
+ value = attn.to_v(hidden_states)
462
+
463
+ # [B, C, T, H, W] -> [B * T, H * W, C]
464
+ query = query.permute(0, 2, 3, 4, 1).flatten(2, 3).flatten(0, 1)
465
+ key = key.permute(0, 2, 3, 4, 1).flatten(2, 3).flatten(0, 1)
466
+ value = value.permute(0, 2, 3, 4, 1).flatten(2, 3).flatten(0, 1)
467
+
468
+ # [B * T, H * W, C] -> [B * T, N, H * W, C // N]
469
+ query = query.unflatten(2, (attn.num_attention_heads, -1)).transpose(1, 2)
470
+ key = key.unflatten(2, (attn.num_attention_heads, -1)).transpose(1, 2)
471
+ value = value.unflatten(2, (attn.num_attention_heads, -1)).transpose(1, 2)
472
+
473
+ hidden_states = F.scaled_dot_product_attention(query, key, value, attn_mask=attention_mask)
474
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3).type_as(query)
475
+ hidden_states = hidden_states.unflatten(1, (height, width)).unflatten(0, (batch_size, num_frames))
476
+ hidden_states = hidden_states.permute(0, 4, 1, 2, 3)
477
+
478
+ hidden_states = attn.to_out[0](hidden_states)
479
+ hidden_states = attn.to_out[1](hidden_states)
480
+
481
+ return hidden_states + residual
482
+
483
+
484
+ class CosmosTemporalAttentionProcessor2_0:
485
+ def __init__(self):
486
+ if not hasattr(F, "scaled_dot_product_attention"):
487
+ raise ImportError(
488
+ "CosmosSpatialAttentionProcessor2_0 requires PyTorch 2.0 or higher. To use it, please upgrade PyTorch."
489
+ )
490
+
491
+ def __call__(
492
+ self, attn: CosmosCausalAttention, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None
493
+ ) -> torch.Tensor:
494
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
495
+ residual = hidden_states
496
+
497
+ hidden_states = attn.norm(hidden_states)
498
+ query = attn.to_q(hidden_states)
499
+ key = attn.to_k(hidden_states)
500
+ value = attn.to_v(hidden_states)
501
+
502
+ # [B, C, T, H, W] -> [B * T, H * W, C]
503
+ query = query.permute(0, 3, 4, 2, 1).flatten(0, 2)
504
+ key = key.permute(0, 3, 4, 2, 1).flatten(0, 2)
505
+ value = value.permute(0, 3, 4, 2, 1).flatten(0, 2)
506
+
507
+ # [B * T, H * W, C] -> [B * T, N, H * W, C // N]
508
+ query = query.unflatten(2, (attn.num_attention_heads, -1)).transpose(1, 2)
509
+ key = key.unflatten(2, (attn.num_attention_heads, -1)).transpose(1, 2)
510
+ value = value.unflatten(2, (attn.num_attention_heads, -1)).transpose(1, 2)
511
+
512
+ hidden_states = F.scaled_dot_product_attention(query, key, value, attn_mask=attention_mask)
513
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3).type_as(query)
514
+ hidden_states = hidden_states.unflatten(0, (batch_size, height, width))
515
+ hidden_states = hidden_states.permute(0, 4, 3, 1, 2)
516
+
517
+ hidden_states = attn.to_out[0](hidden_states)
518
+ hidden_states = attn.to_out[1](hidden_states)
519
+
520
+ return hidden_states + residual
521
+
522
+
523
+ class CosmosDownBlock3d(nn.Module):
524
+ def __init__(
525
+ self,
526
+ in_channels: int,
527
+ out_channels: int,
528
+ num_layers: int,
529
+ dropout: float,
530
+ use_attention: bool,
531
+ use_downsample: bool,
532
+ spatial_downsample: bool,
533
+ temporal_downsample: bool,
534
+ ) -> None:
535
+ super().__init__()
536
+
537
+ resnets, attentions, temp_attentions = [], [], []
538
+ in_channel, out_channel = in_channels, out_channels
539
+
540
+ for _ in range(num_layers):
541
+ resnets.append(CosmosResnetBlock3d(in_channel, out_channel, dropout, num_groups=1))
542
+ in_channel = out_channel
543
+
544
+ if use_attention:
545
+ attentions.append(
546
+ CosmosCausalAttention(
547
+ num_attention_heads=1,
548
+ attention_head_dim=out_channel,
549
+ num_groups=1,
550
+ dropout=dropout,
551
+ processor=CosmosSpatialAttentionProcessor2_0(),
552
+ )
553
+ )
554
+ temp_attentions.append(
555
+ CosmosCausalAttention(
556
+ num_attention_heads=1,
557
+ attention_head_dim=out_channel,
558
+ num_groups=1,
559
+ dropout=dropout,
560
+ processor=CosmosTemporalAttentionProcessor2_0(),
561
+ )
562
+ )
563
+ else:
564
+ attentions.append(None)
565
+ temp_attentions.append(None)
566
+
567
+ self.resnets = nn.ModuleList(resnets)
568
+ self.attentions = nn.ModuleList(attentions)
569
+ self.temp_attentions = nn.ModuleList(temp_attentions)
570
+
571
+ self.downsamplers = None
572
+ if use_downsample:
573
+ self.downsamplers = nn.ModuleList([])
574
+ self.downsamplers.append(CosmosDownsample3d(out_channel, spatial_downsample, temporal_downsample))
575
+
576
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
577
+ for resnet, attention, temp_attention in zip(self.resnets, self.attentions, self.temp_attentions):
578
+ hidden_states = resnet(hidden_states)
579
+ if attention is not None:
580
+ hidden_states = attention(hidden_states)
581
+ if temp_attention is not None:
582
+ num_frames = hidden_states.size(2)
583
+ attention_mask = torch.tril(hidden_states.new_ones(num_frames, num_frames)).bool()
584
+ hidden_states = temp_attention(hidden_states, attention_mask)
585
+
586
+ if self.downsamplers is not None:
587
+ for downsampler in self.downsamplers:
588
+ hidden_states = downsampler(hidden_states)
589
+
590
+ return hidden_states
591
+
592
+
593
+ class CosmosMidBlock3d(nn.Module):
594
+ def __init__(self, in_channels: int, num_layers: int, dropout: float, num_groups: int = 1) -> None:
595
+ super().__init__()
596
+
597
+ resnets, attentions, temp_attentions = [], [], []
598
+
599
+ resnets.append(CosmosResnetBlock3d(in_channels, in_channels, dropout, num_groups))
600
+ for _ in range(num_layers):
601
+ attentions.append(
602
+ CosmosCausalAttention(
603
+ num_attention_heads=1,
604
+ attention_head_dim=in_channels,
605
+ num_groups=num_groups,
606
+ dropout=dropout,
607
+ processor=CosmosSpatialAttentionProcessor2_0(),
608
+ )
609
+ )
610
+ temp_attentions.append(
611
+ CosmosCausalAttention(
612
+ num_attention_heads=1,
613
+ attention_head_dim=in_channels,
614
+ num_groups=num_groups,
615
+ dropout=dropout,
616
+ processor=CosmosTemporalAttentionProcessor2_0(),
617
+ )
618
+ )
619
+ resnets.append(CosmosResnetBlock3d(in_channels, in_channels, dropout, num_groups))
620
+
621
+ self.resnets = nn.ModuleList(resnets)
622
+ self.attentions = nn.ModuleList(attentions)
623
+ self.temp_attentions = nn.ModuleList(temp_attentions)
624
+
625
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
626
+ hidden_states = self.resnets[0](hidden_states)
627
+
628
+ for attention, temp_attention, resnet in zip(self.attentions, self.temp_attentions, self.resnets[1:]):
629
+ num_frames = hidden_states.size(2)
630
+ attention_mask = torch.tril(hidden_states.new_ones(num_frames, num_frames)).bool()
631
+
632
+ hidden_states = attention(hidden_states)
633
+ hidden_states = temp_attention(hidden_states, attention_mask)
634
+ hidden_states = resnet(hidden_states)
635
+
636
+ return hidden_states
637
+
638
+
639
+ class CosmosUpBlock3d(nn.Module):
640
+ def __init__(
641
+ self,
642
+ in_channels: int,
643
+ out_channels: int,
644
+ num_layers: int,
645
+ dropout: float,
646
+ use_attention: bool,
647
+ use_upsample: bool,
648
+ spatial_upsample: bool,
649
+ temporal_upsample: bool,
650
+ ) -> None:
651
+ super().__init__()
652
+
653
+ resnets, attention, temp_attentions = [], [], []
654
+ in_channel, out_channel = in_channels, out_channels
655
+
656
+ for _ in range(num_layers):
657
+ resnets.append(CosmosResnetBlock3d(in_channel, out_channel, dropout, num_groups=1))
658
+ in_channel = out_channel
659
+
660
+ if use_attention:
661
+ attention.append(
662
+ CosmosCausalAttention(
663
+ num_attention_heads=1,
664
+ attention_head_dim=out_channel,
665
+ num_groups=1,
666
+ dropout=dropout,
667
+ processor=CosmosSpatialAttentionProcessor2_0(),
668
+ )
669
+ )
670
+ temp_attentions.append(
671
+ CosmosCausalAttention(
672
+ num_attention_heads=1,
673
+ attention_head_dim=out_channel,
674
+ num_groups=1,
675
+ dropout=dropout,
676
+ processor=CosmosTemporalAttentionProcessor2_0(),
677
+ )
678
+ )
679
+ else:
680
+ attention.append(None)
681
+ temp_attentions.append(None)
682
+
683
+ self.resnets = nn.ModuleList(resnets)
684
+ self.attentions = nn.ModuleList(attention)
685
+ self.temp_attentions = nn.ModuleList(temp_attentions)
686
+
687
+ self.upsamplers = None
688
+ if use_upsample:
689
+ self.upsamplers = nn.ModuleList([])
690
+ self.upsamplers.append(CosmosUpsample3d(out_channel, spatial_upsample, temporal_upsample))
691
+
692
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
693
+ for resnet, attention, temp_attention in zip(self.resnets, self.attentions, self.temp_attentions):
694
+ hidden_states = resnet(hidden_states)
695
+ if attention is not None:
696
+ hidden_states = attention(hidden_states)
697
+ if temp_attention is not None:
698
+ num_frames = hidden_states.size(2)
699
+ attention_mask = torch.tril(hidden_states.new_ones(num_frames, num_frames)).bool()
700
+ hidden_states = temp_attention(hidden_states, attention_mask)
701
+
702
+ if self.upsamplers is not None:
703
+ for upsampler in self.upsamplers:
704
+ hidden_states = upsampler(hidden_states)
705
+
706
+ return hidden_states
707
+
708
+
709
+ class CosmosEncoder3d(nn.Module):
710
+ def __init__(
711
+ self,
712
+ in_channels: int = 3,
713
+ out_channels: int = 16,
714
+ block_out_channels: Tuple[int, ...] = (128, 256, 512, 512),
715
+ num_resnet_blocks: int = 2,
716
+ attention_resolutions: Tuple[int, ...] = (32,),
717
+ resolution: int = 1024,
718
+ patch_size: int = 4,
719
+ patch_type: str = "haar",
720
+ dropout: float = 0.0,
721
+ spatial_compression_ratio: int = 8,
722
+ temporal_compression_ratio: int = 8,
723
+ ) -> None:
724
+ super().__init__()
725
+ inner_dim = in_channels * patch_size**3
726
+ num_spatial_layers = int(math.log2(spatial_compression_ratio)) - int(math.log2(patch_size))
727
+ num_temporal_layers = int(math.log2(temporal_compression_ratio)) - int(math.log2(patch_size))
728
+
729
+ # 1. Input patching & projection
730
+ self.patch_embed = CosmosPatchEmbed3d(patch_size, patch_type)
731
+
732
+ self.conv_in = CosmosConvProjection3d(inner_dim, block_out_channels[0])
733
+
734
+ # 2. Down blocks
735
+ current_resolution = resolution // patch_size
736
+ down_blocks = []
737
+ for i in range(len(block_out_channels) - 1):
738
+ in_channel = block_out_channels[i]
739
+ out_channel = block_out_channels[i + 1]
740
+
741
+ use_attention = current_resolution in attention_resolutions
742
+ spatial_downsample = temporal_downsample = False
743
+ if i < len(block_out_channels) - 2:
744
+ use_downsample = True
745
+ spatial_downsample = i < num_spatial_layers
746
+ temporal_downsample = i < num_temporal_layers
747
+ current_resolution = current_resolution // 2
748
+ else:
749
+ use_downsample = False
750
+
751
+ down_blocks.append(
752
+ CosmosDownBlock3d(
753
+ in_channel,
754
+ out_channel,
755
+ num_resnet_blocks,
756
+ dropout,
757
+ use_attention,
758
+ use_downsample,
759
+ spatial_downsample,
760
+ temporal_downsample,
761
+ )
762
+ )
763
+ self.down_blocks = nn.ModuleList(down_blocks)
764
+
765
+ # 3. Mid block
766
+ self.mid_block = CosmosMidBlock3d(block_out_channels[-1], num_layers=1, dropout=dropout, num_groups=1)
767
+
768
+ # 4. Output norm & projection
769
+ self.norm_out = CosmosCausalGroupNorm(block_out_channels[-1], num_groups=1)
770
+ self.conv_out = CosmosConvProjection3d(block_out_channels[-1], out_channels)
771
+
772
+ self.gradient_checkpointing = False
773
+
774
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
775
+ hidden_states = self.patch_embed(hidden_states)
776
+ hidden_states = self.conv_in(hidden_states)
777
+
778
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
779
+ for block in self.down_blocks:
780
+ hidden_states = self._gradient_checkpointing_func(block, hidden_states)
781
+ hidden_states = self._gradient_checkpointing_func(self.mid_block, hidden_states)
782
+ else:
783
+ for block in self.down_blocks:
784
+ hidden_states = block(hidden_states)
785
+ hidden_states = self.mid_block(hidden_states)
786
+
787
+ hidden_states = self.norm_out(hidden_states)
788
+ hidden_states = F.silu(hidden_states)
789
+ hidden_states = self.conv_out(hidden_states)
790
+ return hidden_states
791
+
792
+
793
+ class CosmosDecoder3d(nn.Module):
794
+ def __init__(
795
+ self,
796
+ in_channels: int = 16,
797
+ out_channels: int = 3,
798
+ block_out_channels: Tuple[int, ...] = (128, 256, 512, 512),
799
+ num_resnet_blocks: int = 2,
800
+ attention_resolutions: Tuple[int, ...] = (32,),
801
+ resolution: int = 1024,
802
+ patch_size: int = 4,
803
+ patch_type: str = "haar",
804
+ dropout: float = 0.0,
805
+ spatial_compression_ratio: int = 8,
806
+ temporal_compression_ratio: int = 8,
807
+ ) -> None:
808
+ super().__init__()
809
+ inner_dim = out_channels * patch_size**3
810
+ num_spatial_layers = int(math.log2(spatial_compression_ratio)) - int(math.log2(patch_size))
811
+ num_temporal_layers = int(math.log2(temporal_compression_ratio)) - int(math.log2(patch_size))
812
+ reversed_block_out_channels = list(reversed(block_out_channels))
813
+
814
+ # 1. Input projection
815
+ self.conv_in = CosmosConvProjection3d(in_channels, reversed_block_out_channels[0])
816
+
817
+ # 2. Mid block
818
+ self.mid_block = CosmosMidBlock3d(reversed_block_out_channels[0], num_layers=1, dropout=dropout, num_groups=1)
819
+
820
+ # 3. Up blocks
821
+ current_resolution = (resolution // patch_size) // 2 ** (len(block_out_channels) - 2)
822
+ up_blocks = []
823
+ for i in range(len(block_out_channels) - 1):
824
+ in_channel = reversed_block_out_channels[i]
825
+ out_channel = reversed_block_out_channels[i + 1]
826
+
827
+ use_attention = current_resolution in attention_resolutions
828
+ spatial_upsample = temporal_upsample = False
829
+ if i < len(block_out_channels) - 2:
830
+ use_upsample = True
831
+ temporal_upsample = 0 < i < num_temporal_layers + 1
832
+ spatial_upsample = temporal_upsample or (
833
+ i < num_spatial_layers and num_spatial_layers > num_temporal_layers
834
+ )
835
+ current_resolution = current_resolution * 2
836
+ else:
837
+ use_upsample = False
838
+
839
+ up_blocks.append(
840
+ CosmosUpBlock3d(
841
+ in_channel,
842
+ out_channel,
843
+ num_resnet_blocks + 1,
844
+ dropout,
845
+ use_attention,
846
+ use_upsample,
847
+ spatial_upsample,
848
+ temporal_upsample,
849
+ )
850
+ )
851
+ self.up_blocks = nn.ModuleList(up_blocks)
852
+
853
+ # 4. Output norm & projection & unpatching
854
+ self.norm_out = CosmosCausalGroupNorm(reversed_block_out_channels[-1], num_groups=1)
855
+ self.conv_out = CosmosConvProjection3d(reversed_block_out_channels[-1], inner_dim)
856
+
857
+ self.unpatch_embed = CosmosUnpatcher3d(patch_size, patch_type)
858
+
859
+ self.gradient_checkpointing = False
860
+
861
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
862
+ hidden_states = self.conv_in(hidden_states)
863
+ hidden_states = self.mid_block(hidden_states)
864
+
865
+ for block in self.up_blocks:
866
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
867
+ hidden_states = self._gradient_checkpointing_func(block, hidden_states)
868
+ else:
869
+ hidden_states = block(hidden_states)
870
+
871
+ hidden_states = self.norm_out(hidden_states)
872
+ hidden_states = F.silu(hidden_states)
873
+ hidden_states = self.conv_out(hidden_states)
874
+ hidden_states = self.unpatch_embed(hidden_states)
875
+ return hidden_states
876
+
877
+
878
+ class AutoencoderKLCosmos(ModelMixin, ConfigMixin):
879
+ r"""
880
+ Autoencoder used in [Cosmos](https://huggingface.co/papers/2501.03575).
881
+
882
+ Args:
883
+ in_channels (`int`, defaults to `3`):
884
+ Number of input channels.
885
+ out_channels (`int`, defaults to `3`):
886
+ Number of output channels.
887
+ latent_channels (`int`, defaults to `16`):
888
+ Number of latent channels.
889
+ encoder_block_out_channels (`Tuple[int, ...]`, defaults to `(128, 256, 512, 512)`):
890
+ Number of output channels for each encoder down block.
891
+ decode_block_out_channels (`Tuple[int, ...]`, defaults to `(256, 512, 512, 512)`):
892
+ Number of output channels for each decoder up block.
893
+ attention_resolutions (`Tuple[int, ...]`, defaults to `(32,)`):
894
+ List of image/video resolutions at which to apply attention.
895
+ resolution (`int`, defaults to `1024`):
896
+ Base image/video resolution used for computing whether a block should have attention layers.
897
+ num_layers (`int`, defaults to `2`):
898
+ Number of resnet blocks in each encoder/decoder block.
899
+ patch_size (`int`, defaults to `4`):
900
+ Patch size used for patching the input image/video.
901
+ patch_type (`str`, defaults to `haar`):
902
+ Patch type used for patching the input image/video. Can be either `haar` or `rearrange`.
903
+ scaling_factor (`float`, defaults to `1.0`):
904
+ The component-wise standard deviation of the trained latent space computed using the first batch of the
905
+ training set. This is used to scale the latent space to have unit variance when training the diffusion
906
+ model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
907
+ diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
908
+ / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
909
+ Synthesis with Latent Diffusion Models](https://huggingface.co/papers/2112.10752) paper. Not applicable in
910
+ Cosmos, but we default to 1.0 for consistency.
911
+ spatial_compression_ratio (`int`, defaults to `8`):
912
+ The spatial compression ratio to apply in the VAE. The number of downsample blocks is determined using
913
+ this.
914
+ temporal_compression_ratio (`int`, defaults to `8`):
915
+ The temporal compression ratio to apply in the VAE. The number of downsample blocks is determined using
916
+ this.
917
+ """
918
+
919
+ _supports_gradient_checkpointing = True
920
+
921
+ @register_to_config
922
+ def __init__(
923
+ self,
924
+ in_channels: int = 3,
925
+ out_channels: int = 3,
926
+ latent_channels: int = 16,
927
+ encoder_block_out_channels: Tuple[int, ...] = (128, 256, 512, 512),
928
+ decode_block_out_channels: Tuple[int, ...] = (256, 512, 512, 512),
929
+ attention_resolutions: Tuple[int, ...] = (32,),
930
+ resolution: int = 1024,
931
+ num_layers: int = 2,
932
+ patch_size: int = 4,
933
+ patch_type: str = "haar",
934
+ scaling_factor: float = 1.0,
935
+ spatial_compression_ratio: int = 8,
936
+ temporal_compression_ratio: int = 8,
937
+ latents_mean: Optional[List[float]] = LATENTS_MEAN,
938
+ latents_std: Optional[List[float]] = LATENTS_STD,
939
+ ) -> None:
940
+ super().__init__()
941
+
942
+ self.encoder = CosmosEncoder3d(
943
+ in_channels=in_channels,
944
+ out_channels=latent_channels,
945
+ block_out_channels=encoder_block_out_channels,
946
+ num_resnet_blocks=num_layers,
947
+ attention_resolutions=attention_resolutions,
948
+ resolution=resolution,
949
+ patch_size=patch_size,
950
+ patch_type=patch_type,
951
+ spatial_compression_ratio=spatial_compression_ratio,
952
+ temporal_compression_ratio=temporal_compression_ratio,
953
+ )
954
+ self.decoder = CosmosDecoder3d(
955
+ in_channels=latent_channels,
956
+ out_channels=out_channels,
957
+ block_out_channels=decode_block_out_channels,
958
+ num_resnet_blocks=num_layers,
959
+ attention_resolutions=attention_resolutions,
960
+ resolution=resolution,
961
+ patch_size=patch_size,
962
+ patch_type=patch_type,
963
+ spatial_compression_ratio=spatial_compression_ratio,
964
+ temporal_compression_ratio=temporal_compression_ratio,
965
+ )
966
+
967
+ self.quant_conv = CosmosCausalConv3d(latent_channels, latent_channels, kernel_size=1, padding=0)
968
+ self.post_quant_conv = CosmosCausalConv3d(latent_channels, latent_channels, kernel_size=1, padding=0)
969
+
970
+ # When decoding a batch of video latents at a time, one can save memory by slicing across the batch dimension
971
+ # to perform decoding of a single video latent at a time.
972
+ self.use_slicing = False
973
+
974
+ # When decoding spatially large video latents, the memory requirement is very high. By breaking the video latent
975
+ # frames spatially into smaller tiles and performing multiple forward passes for decoding, and then blending the
976
+ # intermediate tiles together, the memory requirement can be lowered.
977
+ self.use_tiling = False
978
+
979
+ # When decoding temporally long video latents, the memory requirement is very high. By decoding latent frames
980
+ # at a fixed frame batch size (based on `self.num_latent_frames_batch_sizes`), the memory requirement can be lowered.
981
+ self.use_framewise_encoding = False
982
+ self.use_framewise_decoding = False
983
+
984
+ # This can be configured based on the amount of GPU memory available.
985
+ # `16` for sample frames and `2` for latent frames are sensible defaults for consumer GPUs.
986
+ # Setting it to higher values results in higher memory usage.
987
+ self.num_sample_frames_batch_size = 16
988
+ self.num_latent_frames_batch_size = 2
989
+
990
+ # The minimal tile height and width for spatial tiling to be used
991
+ self.tile_sample_min_height = 512
992
+ self.tile_sample_min_width = 512
993
+ self.tile_sample_min_num_frames = 16
994
+
995
+ # The minimal distance between two spatial tiles
996
+ self.tile_sample_stride_height = 448
997
+ self.tile_sample_stride_width = 448
998
+ self.tile_sample_stride_num_frames = 8
999
+
1000
+ def enable_tiling(
1001
+ self,
1002
+ tile_sample_min_height: Optional[int] = None,
1003
+ tile_sample_min_width: Optional[int] = None,
1004
+ tile_sample_min_num_frames: Optional[int] = None,
1005
+ tile_sample_stride_height: Optional[float] = None,
1006
+ tile_sample_stride_width: Optional[float] = None,
1007
+ tile_sample_stride_num_frames: Optional[float] = None,
1008
+ ) -> None:
1009
+ r"""
1010
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
1011
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
1012
+ processing larger images.
1013
+
1014
+ Args:
1015
+ tile_sample_min_height (`int`, *optional*):
1016
+ The minimum height required for a sample to be separated into tiles across the height dimension.
1017
+ tile_sample_min_width (`int`, *optional*):
1018
+ The minimum width required for a sample to be separated into tiles across the width dimension.
1019
+ tile_sample_stride_height (`int`, *optional*):
1020
+ The minimum amount of overlap between two consecutive vertical tiles. This is to ensure that there are
1021
+ no tiling artifacts produced across the height dimension.
1022
+ tile_sample_stride_width (`int`, *optional*):
1023
+ The stride between two consecutive horizontal tiles. This is to ensure that there are no tiling
1024
+ artifacts produced across the width dimension.
1025
+ """
1026
+ self.use_tiling = True
1027
+ self.tile_sample_min_height = tile_sample_min_height or self.tile_sample_min_height
1028
+ self.tile_sample_min_width = tile_sample_min_width or self.tile_sample_min_width
1029
+ self.tile_sample_min_num_frames = tile_sample_min_num_frames or self.tile_sample_min_num_frames
1030
+ self.tile_sample_stride_height = tile_sample_stride_height or self.tile_sample_stride_height
1031
+ self.tile_sample_stride_width = tile_sample_stride_width or self.tile_sample_stride_width
1032
+ self.tile_sample_stride_num_frames = tile_sample_stride_num_frames or self.tile_sample_stride_num_frames
1033
+
1034
+ def disable_tiling(self) -> None:
1035
+ r"""
1036
+ Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
1037
+ decoding in one step.
1038
+ """
1039
+ self.use_tiling = False
1040
+
1041
+ def enable_slicing(self) -> None:
1042
+ r"""
1043
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
1044
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
1045
+ """
1046
+ self.use_slicing = True
1047
+
1048
+ def disable_slicing(self) -> None:
1049
+ r"""
1050
+ Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
1051
+ decoding in one step.
1052
+ """
1053
+ self.use_slicing = False
1054
+
1055
+ def _encode(self, x: torch.Tensor) -> torch.Tensor:
1056
+ x = self.encoder(x)
1057
+ enc = self.quant_conv(x)
1058
+ return enc
1059
+
1060
+ @apply_forward_hook
1061
+ def encode(self, x: torch.Tensor, return_dict: bool = True) -> torch.Tensor:
1062
+ if self.use_slicing and x.shape[0] > 1:
1063
+ encoded_slices = [self._encode(x_slice) for x_slice in x.split(1)]
1064
+ h = torch.cat(encoded_slices)
1065
+ else:
1066
+ h = self._encode(x)
1067
+
1068
+ posterior = IdentityDistribution(h)
1069
+
1070
+ if not return_dict:
1071
+ return (posterior,)
1072
+ return AutoencoderKLOutput(latent_dist=posterior)
1073
+
1074
+ def _decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, Tuple[torch.Tensor]]:
1075
+ z = self.post_quant_conv(z)
1076
+ dec = self.decoder(z)
1077
+
1078
+ if not return_dict:
1079
+ return (dec,)
1080
+ return DecoderOutput(sample=dec)
1081
+
1082
+ @apply_forward_hook
1083
+ def decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, Tuple[torch.Tensor]]:
1084
+ if self.use_slicing and z.shape[0] > 1:
1085
+ decoded_slices = [self._decode(z_slice).sample for z_slice in z.split(1)]
1086
+ decoded = torch.cat(decoded_slices)
1087
+ else:
1088
+ decoded = self._decode(z).sample
1089
+
1090
+ if not return_dict:
1091
+ return (decoded,)
1092
+ return DecoderOutput(sample=decoded)
1093
+
1094
+ def forward(
1095
+ self,
1096
+ sample: torch.Tensor,
1097
+ sample_posterior: bool = False,
1098
+ return_dict: bool = True,
1099
+ generator: Optional[torch.Generator] = None,
1100
+ ) -> Union[Tuple[torch.Tensor], DecoderOutput]:
1101
+ x = sample
1102
+ posterior = self.encode(x).latent_dist
1103
+ if sample_posterior:
1104
+ z = posterior.sample(generator=generator)
1105
+ else:
1106
+ z = posterior.mode()
1107
+ dec = self.decode(z).sample
1108
+ if not return_dict:
1109
+ return (dec,)
1110
+ return DecoderOutput(sample=dec)