diffusers 0.33.0__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 +17 -12
  388. diffusers/pipelines/wan/pipeline_wan_i2v.py +42 -20
  389. diffusers/pipelines/wan/pipeline_wan_vace.py +976 -0
  390. diffusers/pipelines/wan/pipeline_wan_video2video.py +18 -18
  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.0.dist-info → diffusers-0.34.0.dist-info}/METADATA +3 -3
  473. diffusers-0.34.0.dist-info/RECORD +639 -0
  474. diffusers-0.33.0.dist-info/RECORD +0 -608
  475. {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/LICENSE +0 -0
  476. {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/WHEEL +0 -0
  477. {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/entry_points.txt +0 -0
  478. {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1106 @@
1
+ # Copyright 2025 PixArt-Sigma Authors and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import html
16
+ import inspect
17
+ import re
18
+ import urllib.parse as ul
19
+ import warnings
20
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ from transformers import Gemma2PreTrainedModel, GemmaTokenizer, GemmaTokenizerFast
24
+
25
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
26
+ from ...image_processor import PipelineImageInput, PixArtImageProcessor
27
+ from ...loaders import SanaLoraLoaderMixin
28
+ from ...models import AutoencoderDC, SanaControlNetModel, SanaTransformer2DModel
29
+ from ...schedulers import DPMSolverMultistepScheduler
30
+ from ...utils import (
31
+ BACKENDS_MAPPING,
32
+ USE_PEFT_BACKEND,
33
+ is_bs4_available,
34
+ is_ftfy_available,
35
+ is_torch_xla_available,
36
+ logging,
37
+ replace_example_docstring,
38
+ scale_lora_layers,
39
+ unscale_lora_layers,
40
+ )
41
+ from ...utils.torch_utils import get_device, is_torch_version, randn_tensor
42
+ from ..pipeline_utils import DiffusionPipeline
43
+ from ..pixart_alpha.pipeline_pixart_alpha import (
44
+ ASPECT_RATIO_512_BIN,
45
+ ASPECT_RATIO_1024_BIN,
46
+ )
47
+ from ..pixart_alpha.pipeline_pixart_sigma import ASPECT_RATIO_2048_BIN
48
+ from .pipeline_output import SanaPipelineOutput
49
+
50
+
51
+ if is_torch_xla_available():
52
+ import torch_xla.core.xla_model as xm
53
+
54
+ XLA_AVAILABLE = True
55
+ else:
56
+ XLA_AVAILABLE = False
57
+
58
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
59
+
60
+ if is_bs4_available():
61
+ from bs4 import BeautifulSoup
62
+
63
+ if is_ftfy_available():
64
+ import ftfy
65
+
66
+
67
+ ASPECT_RATIO_4096_BIN = {
68
+ "0.25": [2048.0, 8192.0],
69
+ "0.26": [2048.0, 7936.0],
70
+ "0.27": [2048.0, 7680.0],
71
+ "0.28": [2048.0, 7424.0],
72
+ "0.32": [2304.0, 7168.0],
73
+ "0.33": [2304.0, 6912.0],
74
+ "0.35": [2304.0, 6656.0],
75
+ "0.4": [2560.0, 6400.0],
76
+ "0.42": [2560.0, 6144.0],
77
+ "0.48": [2816.0, 5888.0],
78
+ "0.5": [2816.0, 5632.0],
79
+ "0.52": [2816.0, 5376.0],
80
+ "0.57": [3072.0, 5376.0],
81
+ "0.6": [3072.0, 5120.0],
82
+ "0.68": [3328.0, 4864.0],
83
+ "0.72": [3328.0, 4608.0],
84
+ "0.78": [3584.0, 4608.0],
85
+ "0.82": [3584.0, 4352.0],
86
+ "0.88": [3840.0, 4352.0],
87
+ "0.94": [3840.0, 4096.0],
88
+ "1.0": [4096.0, 4096.0],
89
+ "1.07": [4096.0, 3840.0],
90
+ "1.13": [4352.0, 3840.0],
91
+ "1.21": [4352.0, 3584.0],
92
+ "1.29": [4608.0, 3584.0],
93
+ "1.38": [4608.0, 3328.0],
94
+ "1.46": [4864.0, 3328.0],
95
+ "1.67": [5120.0, 3072.0],
96
+ "1.75": [5376.0, 3072.0],
97
+ "2.0": [5632.0, 2816.0],
98
+ "2.09": [5888.0, 2816.0],
99
+ "2.4": [6144.0, 2560.0],
100
+ "2.5": [6400.0, 2560.0],
101
+ "2.89": [6656.0, 2304.0],
102
+ "3.0": [6912.0, 2304.0],
103
+ "3.11": [7168.0, 2304.0],
104
+ "3.62": [7424.0, 2048.0],
105
+ "3.75": [7680.0, 2048.0],
106
+ "3.88": [7936.0, 2048.0],
107
+ "4.0": [8192.0, 2048.0],
108
+ }
109
+
110
+ EXAMPLE_DOC_STRING = """
111
+ Examples:
112
+ ```py
113
+ >>> import torch
114
+ >>> from diffusers import SanaControlNetPipeline
115
+ >>> from diffusers.utils import load_image
116
+
117
+ >>> pipe = SanaControlNetPipeline.from_pretrained(
118
+ ... "ishan24/Sana_600M_1024px_ControlNetPlus_diffusers",
119
+ ... variant="fp16",
120
+ ... torch_dtype={"default": torch.bfloat16, "controlnet": torch.float16, "transformer": torch.float16},
121
+ ... device_map="balanced",
122
+ ... )
123
+ >>> cond_image = load_image(
124
+ ... "https://huggingface.co/ishan24/Sana_600M_1024px_ControlNet_diffusers/resolve/main/hed_example.png"
125
+ ... )
126
+ >>> prompt = 'a cat with a neon sign that says "Sana"'
127
+ >>> image = pipe(
128
+ ... prompt,
129
+ ... control_image=cond_image,
130
+ ... ).images[0]
131
+ >>> image.save("output.png")
132
+ ```
133
+ """
134
+
135
+
136
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
137
+ def retrieve_timesteps(
138
+ scheduler,
139
+ num_inference_steps: Optional[int] = None,
140
+ device: Optional[Union[str, torch.device]] = None,
141
+ timesteps: Optional[List[int]] = None,
142
+ sigmas: Optional[List[float]] = None,
143
+ **kwargs,
144
+ ):
145
+ r"""
146
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
147
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
148
+
149
+ Args:
150
+ scheduler (`SchedulerMixin`):
151
+ The scheduler to get timesteps from.
152
+ num_inference_steps (`int`):
153
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
154
+ must be `None`.
155
+ device (`str` or `torch.device`, *optional*):
156
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
157
+ timesteps (`List[int]`, *optional*):
158
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
159
+ `num_inference_steps` and `sigmas` must be `None`.
160
+ sigmas (`List[float]`, *optional*):
161
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
162
+ `num_inference_steps` and `timesteps` must be `None`.
163
+
164
+ Returns:
165
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
166
+ second element is the number of inference steps.
167
+ """
168
+ if timesteps is not None and sigmas is not None:
169
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
170
+ if timesteps is not None:
171
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
172
+ if not accepts_timesteps:
173
+ raise ValueError(
174
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
175
+ f" timestep schedules. Please check whether you are using the correct scheduler."
176
+ )
177
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
178
+ timesteps = scheduler.timesteps
179
+ num_inference_steps = len(timesteps)
180
+ elif sigmas is not None:
181
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
182
+ if not accept_sigmas:
183
+ raise ValueError(
184
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
185
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
186
+ )
187
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
188
+ timesteps = scheduler.timesteps
189
+ num_inference_steps = len(timesteps)
190
+ else:
191
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
192
+ timesteps = scheduler.timesteps
193
+ return timesteps, num_inference_steps
194
+
195
+
196
+ class SanaControlNetPipeline(DiffusionPipeline, SanaLoraLoaderMixin):
197
+ r"""
198
+ Pipeline for text-to-image generation using [Sana](https://huggingface.co/papers/2410.10629).
199
+ """
200
+
201
+ # fmt: off
202
+ bad_punct_regex = re.compile(r"[" + "#®•©™&@·º½¾¿¡§~" + r"\)" + r"\(" + r"\]" + r"\[" + r"\}" + r"\{" + r"\|" + "\\" + r"\/" + r"\*" + r"]{1,}")
203
+ # fmt: on
204
+
205
+ model_cpu_offload_seq = "text_encoder->controlnet->transformer->vae"
206
+ _callback_tensor_inputs = ["latents", "control_image", "prompt_embeds", "negative_prompt_embeds"]
207
+
208
+ def __init__(
209
+ self,
210
+ tokenizer: Union[GemmaTokenizer, GemmaTokenizerFast],
211
+ text_encoder: Gemma2PreTrainedModel,
212
+ vae: AutoencoderDC,
213
+ transformer: SanaTransformer2DModel,
214
+ controlnet: SanaControlNetModel,
215
+ scheduler: DPMSolverMultistepScheduler,
216
+ ):
217
+ super().__init__()
218
+
219
+ self.register_modules(
220
+ tokenizer=tokenizer,
221
+ text_encoder=text_encoder,
222
+ vae=vae,
223
+ transformer=transformer,
224
+ controlnet=controlnet,
225
+ scheduler=scheduler,
226
+ )
227
+
228
+ self.vae_scale_factor = (
229
+ 2 ** (len(self.vae.config.encoder_block_out_channels) - 1)
230
+ if hasattr(self, "vae") and self.vae is not None
231
+ else 32
232
+ )
233
+ self.image_processor = PixArtImageProcessor(vae_scale_factor=self.vae_scale_factor)
234
+
235
+ def enable_vae_slicing(self):
236
+ r"""
237
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
238
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
239
+ """
240
+ self.vae.enable_slicing()
241
+
242
+ def disable_vae_slicing(self):
243
+ r"""
244
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
245
+ computing decoding in one step.
246
+ """
247
+ self.vae.disable_slicing()
248
+
249
+ def enable_vae_tiling(self):
250
+ r"""
251
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
252
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
253
+ processing larger images.
254
+ """
255
+ self.vae.enable_tiling()
256
+
257
+ def disable_vae_tiling(self):
258
+ r"""
259
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
260
+ computing decoding in one step.
261
+ """
262
+ self.vae.disable_tiling()
263
+
264
+ # Copied from diffusers.pipelines.sana.pipeline_sana.SanaPipeline._get_gemma_prompt_embeds
265
+ def _get_gemma_prompt_embeds(
266
+ self,
267
+ prompt: Union[str, List[str]],
268
+ device: torch.device,
269
+ dtype: torch.dtype,
270
+ clean_caption: bool = False,
271
+ max_sequence_length: int = 300,
272
+ complex_human_instruction: Optional[List[str]] = None,
273
+ ):
274
+ r"""
275
+ Encodes the prompt into text encoder hidden states.
276
+
277
+ Args:
278
+ prompt (`str` or `List[str]`, *optional*):
279
+ prompt to be encoded
280
+ device: (`torch.device`, *optional*):
281
+ torch device to place the resulting embeddings on
282
+ clean_caption (`bool`, defaults to `False`):
283
+ If `True`, the function will preprocess and clean the provided caption before encoding.
284
+ max_sequence_length (`int`, defaults to 300): Maximum sequence length to use for the prompt.
285
+ complex_human_instruction (`list[str]`, defaults to `complex_human_instruction`):
286
+ If `complex_human_instruction` is not empty, the function will use the complex Human instruction for
287
+ the prompt.
288
+ """
289
+ prompt = [prompt] if isinstance(prompt, str) else prompt
290
+
291
+ if getattr(self, "tokenizer", None) is not None:
292
+ self.tokenizer.padding_side = "right"
293
+
294
+ prompt = self._text_preprocessing(prompt, clean_caption=clean_caption)
295
+
296
+ # prepare complex human instruction
297
+ if not complex_human_instruction:
298
+ max_length_all = max_sequence_length
299
+ else:
300
+ chi_prompt = "\n".join(complex_human_instruction)
301
+ prompt = [chi_prompt + p for p in prompt]
302
+ num_chi_prompt_tokens = len(self.tokenizer.encode(chi_prompt))
303
+ max_length_all = num_chi_prompt_tokens + max_sequence_length - 2
304
+
305
+ text_inputs = self.tokenizer(
306
+ prompt,
307
+ padding="max_length",
308
+ max_length=max_length_all,
309
+ truncation=True,
310
+ add_special_tokens=True,
311
+ return_tensors="pt",
312
+ )
313
+ text_input_ids = text_inputs.input_ids
314
+
315
+ prompt_attention_mask = text_inputs.attention_mask
316
+ prompt_attention_mask = prompt_attention_mask.to(device)
317
+
318
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=prompt_attention_mask)
319
+ prompt_embeds = prompt_embeds[0].to(dtype=dtype, device=device)
320
+
321
+ return prompt_embeds, prompt_attention_mask
322
+
323
+ # Copied from diffusers.pipelines.sana.pipeline_sana.SanaPipeline.encode_prompt
324
+ def encode_prompt(
325
+ self,
326
+ prompt: Union[str, List[str]],
327
+ do_classifier_free_guidance: bool = True,
328
+ negative_prompt: str = "",
329
+ num_images_per_prompt: int = 1,
330
+ device: Optional[torch.device] = None,
331
+ prompt_embeds: Optional[torch.Tensor] = None,
332
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
333
+ prompt_attention_mask: Optional[torch.Tensor] = None,
334
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
335
+ clean_caption: bool = False,
336
+ max_sequence_length: int = 300,
337
+ complex_human_instruction: Optional[List[str]] = None,
338
+ lora_scale: Optional[float] = None,
339
+ ):
340
+ r"""
341
+ Encodes the prompt into text encoder hidden states.
342
+
343
+ Args:
344
+ prompt (`str` or `List[str]`, *optional*):
345
+ prompt to be encoded
346
+ negative_prompt (`str` or `List[str]`, *optional*):
347
+ The prompt not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds`
348
+ instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). For
349
+ PixArt-Alpha, this should be "".
350
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
351
+ whether to use classifier free guidance or not
352
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
353
+ number of images that should be generated per prompt
354
+ device: (`torch.device`, *optional*):
355
+ torch device to place the resulting embeddings on
356
+ prompt_embeds (`torch.Tensor`, *optional*):
357
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
358
+ provided, text embeddings will be generated from `prompt` input argument.
359
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
360
+ Pre-generated negative text embeddings. For Sana, it's should be the embeddings of the "" string.
361
+ clean_caption (`bool`, defaults to `False`):
362
+ If `True`, the function will preprocess and clean the provided caption before encoding.
363
+ max_sequence_length (`int`, defaults to 300): Maximum sequence length to use for the prompt.
364
+ complex_human_instruction (`list[str]`, defaults to `complex_human_instruction`):
365
+ If `complex_human_instruction` is not empty, the function will use the complex Human instruction for
366
+ the prompt.
367
+ """
368
+
369
+ if device is None:
370
+ device = self._execution_device
371
+
372
+ if self.text_encoder is not None:
373
+ dtype = self.text_encoder.dtype
374
+ else:
375
+ dtype = None
376
+
377
+ # set lora scale so that monkey patched LoRA
378
+ # function of text encoder can correctly access it
379
+ if lora_scale is not None and isinstance(self, SanaLoraLoaderMixin):
380
+ self._lora_scale = lora_scale
381
+
382
+ # dynamically adjust the LoRA scale
383
+ if self.text_encoder is not None and USE_PEFT_BACKEND:
384
+ scale_lora_layers(self.text_encoder, lora_scale)
385
+
386
+ if prompt is not None and isinstance(prompt, str):
387
+ batch_size = 1
388
+ elif prompt is not None and isinstance(prompt, list):
389
+ batch_size = len(prompt)
390
+ else:
391
+ batch_size = prompt_embeds.shape[0]
392
+
393
+ if getattr(self, "tokenizer", None) is not None:
394
+ self.tokenizer.padding_side = "right"
395
+
396
+ # See Section 3.1. of the paper.
397
+ max_length = max_sequence_length
398
+ select_index = [0] + list(range(-max_length + 1, 0))
399
+
400
+ if prompt_embeds is None:
401
+ prompt_embeds, prompt_attention_mask = self._get_gemma_prompt_embeds(
402
+ prompt=prompt,
403
+ device=device,
404
+ dtype=dtype,
405
+ clean_caption=clean_caption,
406
+ max_sequence_length=max_sequence_length,
407
+ complex_human_instruction=complex_human_instruction,
408
+ )
409
+
410
+ prompt_embeds = prompt_embeds[:, select_index]
411
+ prompt_attention_mask = prompt_attention_mask[:, select_index]
412
+
413
+ bs_embed, seq_len, _ = prompt_embeds.shape
414
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
415
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
416
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
417
+ prompt_attention_mask = prompt_attention_mask.view(bs_embed, -1)
418
+ prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)
419
+
420
+ # get unconditional embeddings for classifier free guidance
421
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
422
+ negative_prompt = [negative_prompt] * batch_size if isinstance(negative_prompt, str) else negative_prompt
423
+ negative_prompt_embeds, negative_prompt_attention_mask = self._get_gemma_prompt_embeds(
424
+ prompt=negative_prompt,
425
+ device=device,
426
+ dtype=dtype,
427
+ clean_caption=clean_caption,
428
+ max_sequence_length=max_sequence_length,
429
+ complex_human_instruction=False,
430
+ )
431
+
432
+ if do_classifier_free_guidance:
433
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
434
+ seq_len = negative_prompt_embeds.shape[1]
435
+
436
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
437
+
438
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
439
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
440
+
441
+ negative_prompt_attention_mask = negative_prompt_attention_mask.view(bs_embed, -1)
442
+ negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(num_images_per_prompt, 1)
443
+ else:
444
+ negative_prompt_embeds = None
445
+ negative_prompt_attention_mask = None
446
+
447
+ if self.text_encoder is not None:
448
+ if isinstance(self, SanaLoraLoaderMixin) and USE_PEFT_BACKEND:
449
+ # Retrieve the original scale by scaling back the LoRA layers
450
+ unscale_lora_layers(self.text_encoder, lora_scale)
451
+
452
+ return prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask
453
+
454
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
455
+ def prepare_extra_step_kwargs(self, generator, eta):
456
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
457
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
458
+ # eta corresponds to η in DDIM paper: https://huggingface.co/papers/2010.02502
459
+ # and should be between [0, 1]
460
+
461
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
462
+ extra_step_kwargs = {}
463
+ if accepts_eta:
464
+ extra_step_kwargs["eta"] = eta
465
+
466
+ # check if the scheduler accepts generator
467
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
468
+ if accepts_generator:
469
+ extra_step_kwargs["generator"] = generator
470
+ return extra_step_kwargs
471
+
472
+ def check_inputs(
473
+ self,
474
+ prompt,
475
+ height,
476
+ width,
477
+ callback_on_step_end_tensor_inputs=None,
478
+ negative_prompt=None,
479
+ prompt_embeds=None,
480
+ negative_prompt_embeds=None,
481
+ prompt_attention_mask=None,
482
+ negative_prompt_attention_mask=None,
483
+ ):
484
+ if height % 32 != 0 or width % 32 != 0:
485
+ raise ValueError(f"`height` and `width` have to be divisible by 32 but are {height} and {width}.")
486
+
487
+ if callback_on_step_end_tensor_inputs is not None and not all(
488
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
489
+ ):
490
+ raise ValueError(
491
+ 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]}"
492
+ )
493
+
494
+ if prompt is not None and prompt_embeds is not None:
495
+ raise ValueError(
496
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
497
+ " only forward one of the two."
498
+ )
499
+ elif prompt is None and prompt_embeds is None:
500
+ raise ValueError(
501
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
502
+ )
503
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
504
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
505
+
506
+ if prompt is not None and negative_prompt_embeds is not None:
507
+ raise ValueError(
508
+ f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:"
509
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
510
+ )
511
+
512
+ if negative_prompt is not None and negative_prompt_embeds is not None:
513
+ raise ValueError(
514
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
515
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
516
+ )
517
+
518
+ if prompt_embeds is not None and prompt_attention_mask is None:
519
+ raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.")
520
+
521
+ if negative_prompt_embeds is not None and negative_prompt_attention_mask is None:
522
+ raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.")
523
+
524
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
525
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
526
+ raise ValueError(
527
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
528
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
529
+ f" {negative_prompt_embeds.shape}."
530
+ )
531
+ if prompt_attention_mask.shape != negative_prompt_attention_mask.shape:
532
+ raise ValueError(
533
+ "`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when passed directly, but"
534
+ f" got: `prompt_attention_mask` {prompt_attention_mask.shape} != `negative_prompt_attention_mask`"
535
+ f" {negative_prompt_attention_mask.shape}."
536
+ )
537
+
538
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._text_preprocessing
539
+ def _text_preprocessing(self, text, clean_caption=False):
540
+ if clean_caption and not is_bs4_available():
541
+ logger.warning(BACKENDS_MAPPING["bs4"][-1].format("Setting `clean_caption=True`"))
542
+ logger.warning("Setting `clean_caption` to False...")
543
+ clean_caption = False
544
+
545
+ if clean_caption and not is_ftfy_available():
546
+ logger.warning(BACKENDS_MAPPING["ftfy"][-1].format("Setting `clean_caption=True`"))
547
+ logger.warning("Setting `clean_caption` to False...")
548
+ clean_caption = False
549
+
550
+ if not isinstance(text, (tuple, list)):
551
+ text = [text]
552
+
553
+ def process(text: str):
554
+ if clean_caption:
555
+ text = self._clean_caption(text)
556
+ text = self._clean_caption(text)
557
+ else:
558
+ text = text.lower().strip()
559
+ return text
560
+
561
+ return [process(t) for t in text]
562
+
563
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._clean_caption
564
+ def _clean_caption(self, caption):
565
+ caption = str(caption)
566
+ caption = ul.unquote_plus(caption)
567
+ caption = caption.strip().lower()
568
+ caption = re.sub("<person>", "person", caption)
569
+ # urls:
570
+ caption = re.sub(
571
+ r"\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa
572
+ "",
573
+ caption,
574
+ ) # regex for urls
575
+ caption = re.sub(
576
+ r"\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa
577
+ "",
578
+ caption,
579
+ ) # regex for urls
580
+ # html:
581
+ caption = BeautifulSoup(caption, features="html.parser").text
582
+
583
+ # @<nickname>
584
+ caption = re.sub(r"@[\w\d]+\b", "", caption)
585
+
586
+ # 31C0—31EF CJK Strokes
587
+ # 31F0—31FF Katakana Phonetic Extensions
588
+ # 3200—32FF Enclosed CJK Letters and Months
589
+ # 3300—33FF CJK Compatibility
590
+ # 3400—4DBF CJK Unified Ideographs Extension A
591
+ # 4DC0—4DFF Yijing Hexagram Symbols
592
+ # 4E00—9FFF CJK Unified Ideographs
593
+ caption = re.sub(r"[\u31c0-\u31ef]+", "", caption)
594
+ caption = re.sub(r"[\u31f0-\u31ff]+", "", caption)
595
+ caption = re.sub(r"[\u3200-\u32ff]+", "", caption)
596
+ caption = re.sub(r"[\u3300-\u33ff]+", "", caption)
597
+ caption = re.sub(r"[\u3400-\u4dbf]+", "", caption)
598
+ caption = re.sub(r"[\u4dc0-\u4dff]+", "", caption)
599
+ caption = re.sub(r"[\u4e00-\u9fff]+", "", caption)
600
+ #######################################################
601
+
602
+ # все виды тире / all types of dash --> "-"
603
+ caption = re.sub(
604
+ r"[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+", # noqa
605
+ "-",
606
+ caption,
607
+ )
608
+
609
+ # кавычки к одному стандарту
610
+ caption = re.sub(r"[`´«»“”¨]", '"', caption)
611
+ caption = re.sub(r"[‘’]", "'", caption)
612
+
613
+ # &quot;
614
+ caption = re.sub(r"&quot;?", "", caption)
615
+ # &amp
616
+ caption = re.sub(r"&amp", "", caption)
617
+
618
+ # ip addresses:
619
+ caption = re.sub(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", " ", caption)
620
+
621
+ # article ids:
622
+ caption = re.sub(r"\d:\d\d\s+$", "", caption)
623
+
624
+ # \n
625
+ caption = re.sub(r"\\n", " ", caption)
626
+
627
+ # "#123"
628
+ caption = re.sub(r"#\d{1,3}\b", "", caption)
629
+ # "#12345.."
630
+ caption = re.sub(r"#\d{5,}\b", "", caption)
631
+ # "123456.."
632
+ caption = re.sub(r"\b\d{6,}\b", "", caption)
633
+ # filenames:
634
+ caption = re.sub(r"[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)", "", caption)
635
+
636
+ #
637
+ caption = re.sub(r"[\"\']{2,}", r'"', caption) # """AUSVERKAUFT"""
638
+ caption = re.sub(r"[\.]{2,}", r" ", caption) # """AUSVERKAUFT"""
639
+
640
+ caption = re.sub(self.bad_punct_regex, r" ", caption) # ***AUSVERKAUFT***, #AUSVERKAUFT
641
+ caption = re.sub(r"\s+\.\s+", r" ", caption) # " . "
642
+
643
+ # this-is-my-cute-cat / this_is_my_cute_cat
644
+ regex2 = re.compile(r"(?:\-|\_)")
645
+ if len(re.findall(regex2, caption)) > 3:
646
+ caption = re.sub(regex2, " ", caption)
647
+
648
+ caption = ftfy.fix_text(caption)
649
+ caption = html.unescape(html.unescape(caption))
650
+
651
+ caption = re.sub(r"\b[a-zA-Z]{1,3}\d{3,15}\b", "", caption) # jc6640
652
+ caption = re.sub(r"\b[a-zA-Z]+\d+[a-zA-Z]+\b", "", caption) # jc6640vc
653
+ caption = re.sub(r"\b\d+[a-zA-Z]+\d+\b", "", caption) # 6640vc231
654
+
655
+ caption = re.sub(r"(worldwide\s+)?(free\s+)?shipping", "", caption)
656
+ caption = re.sub(r"(free\s)?download(\sfree)?", "", caption)
657
+ caption = re.sub(r"\bclick\b\s(?:for|on)\s\w+", "", caption)
658
+ caption = re.sub(r"\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?", "", caption)
659
+ caption = re.sub(r"\bpage\s+\d+\b", "", caption)
660
+
661
+ caption = re.sub(r"\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\b", r" ", caption) # j2d1a2a...
662
+
663
+ caption = re.sub(r"\b\d+\.?\d*[xх×]\d+\.?\d*\b", "", caption)
664
+
665
+ caption = re.sub(r"\b\s+\:\s+", r": ", caption)
666
+ caption = re.sub(r"(\D[,\./])\b", r"\1 ", caption)
667
+ caption = re.sub(r"\s+", " ", caption)
668
+
669
+ caption.strip()
670
+
671
+ caption = re.sub(r"^[\"\']([\w\W]+)[\"\']$", r"\1", caption)
672
+ caption = re.sub(r"^[\'\_,\-\:;]", r"", caption)
673
+ caption = re.sub(r"[\'\_,\-\:\-\+]$", r"", caption)
674
+ caption = re.sub(r"^\.\S+$", "", caption)
675
+
676
+ return caption.strip()
677
+
678
+ def prepare_image(
679
+ self,
680
+ image,
681
+ width,
682
+ height,
683
+ batch_size,
684
+ num_images_per_prompt,
685
+ device,
686
+ dtype,
687
+ do_classifier_free_guidance=False,
688
+ guess_mode=False,
689
+ ):
690
+ if isinstance(image, torch.Tensor):
691
+ pass
692
+ else:
693
+ image = self.image_processor.preprocess(image, height=height, width=width)
694
+
695
+ image_batch_size = image.shape[0]
696
+
697
+ if image_batch_size == 1:
698
+ repeat_by = batch_size
699
+ else:
700
+ # image batch size is the same as prompt batch size
701
+ repeat_by = num_images_per_prompt
702
+
703
+ image = image.repeat_interleave(repeat_by, dim=0)
704
+
705
+ image = image.to(device=device, dtype=dtype)
706
+
707
+ if do_classifier_free_guidance and not guess_mode:
708
+ image = torch.cat([image] * 2)
709
+
710
+ return image
711
+
712
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
713
+ if latents is not None:
714
+ return latents.to(device=device, dtype=dtype)
715
+
716
+ shape = (
717
+ batch_size,
718
+ num_channels_latents,
719
+ int(height) // self.vae_scale_factor,
720
+ int(width) // self.vae_scale_factor,
721
+ )
722
+ if isinstance(generator, list) and len(generator) != batch_size:
723
+ raise ValueError(
724
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
725
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
726
+ )
727
+
728
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
729
+ return latents
730
+
731
+ @property
732
+ def guidance_scale(self):
733
+ return self._guidance_scale
734
+
735
+ @property
736
+ def attention_kwargs(self):
737
+ return self._attention_kwargs
738
+
739
+ @property
740
+ def do_classifier_free_guidance(self):
741
+ return self._guidance_scale > 1.0
742
+
743
+ @property
744
+ def num_timesteps(self):
745
+ return self._num_timesteps
746
+
747
+ @property
748
+ def interrupt(self):
749
+ return self._interrupt
750
+
751
+ @torch.no_grad()
752
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
753
+ def __call__(
754
+ self,
755
+ prompt: Union[str, List[str]] = None,
756
+ negative_prompt: str = "",
757
+ num_inference_steps: int = 20,
758
+ timesteps: List[int] = None,
759
+ sigmas: List[float] = None,
760
+ guidance_scale: float = 4.5,
761
+ control_image: PipelineImageInput = None,
762
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
763
+ num_images_per_prompt: Optional[int] = 1,
764
+ height: int = 1024,
765
+ width: int = 1024,
766
+ eta: float = 0.0,
767
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
768
+ latents: Optional[torch.Tensor] = None,
769
+ prompt_embeds: Optional[torch.Tensor] = None,
770
+ prompt_attention_mask: Optional[torch.Tensor] = None,
771
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
772
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
773
+ output_type: Optional[str] = "pil",
774
+ return_dict: bool = True,
775
+ clean_caption: bool = False,
776
+ use_resolution_binning: bool = True,
777
+ attention_kwargs: Optional[Dict[str, Any]] = None,
778
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
779
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
780
+ max_sequence_length: int = 300,
781
+ complex_human_instruction: List[str] = [
782
+ "Given a user prompt, generate an 'Enhanced prompt' that provides detailed visual descriptions suitable for image generation. Evaluate the level of detail in the user prompt:",
783
+ "- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, and spatial relationships to create vivid and concrete scenes.",
784
+ "- If the prompt is already detailed, refine and enhance the existing details slightly without overcomplicating.",
785
+ "Here are examples of how to transform or refine prompts:",
786
+ "- User Prompt: A cat sleeping -> Enhanced: A small, fluffy white cat curled up in a round shape, sleeping peacefully on a warm sunny windowsill, surrounded by pots of blooming red flowers.",
787
+ "- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps, a diverse crowd of people in colorful clothing, and a double-decker bus passing by towering glass skyscrapers.",
788
+ "Please generate only the enhanced description for the prompt below and avoid including any additional commentary or evaluations:",
789
+ "User Prompt: ",
790
+ ],
791
+ ) -> Union[SanaPipelineOutput, Tuple]:
792
+ """
793
+ Function invoked when calling the pipeline for generation.
794
+
795
+ Args:
796
+ prompt (`str` or `List[str]`, *optional*):
797
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
798
+ instead.
799
+ negative_prompt (`str` or `List[str]`, *optional*):
800
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
801
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
802
+ less than `1`).
803
+ num_inference_steps (`int`, *optional*, defaults to 20):
804
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
805
+ expense of slower inference.
806
+ timesteps (`List[int]`, *optional*):
807
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
808
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
809
+ passed will be used. Must be in descending order.
810
+ sigmas (`List[float]`, *optional*):
811
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
812
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
813
+ will be used.
814
+ guidance_scale (`float`, *optional*, defaults to 4.5):
815
+ Guidance scale as defined in [Classifier-Free Diffusion
816
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
817
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
818
+ `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
819
+ the text `prompt`, usually at the expense of lower image quality.
820
+ control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
821
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
822
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
823
+ specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted
824
+ as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or
825
+ width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`,
826
+ images must be passed as a list such that each element of the list can be correctly batched for input
827
+ to a single ControlNet.
828
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
829
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
830
+ to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
831
+ the corresponding scale as a list.
832
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
833
+ The number of images to generate per prompt.
834
+ height (`int`, *optional*, defaults to self.unet.config.sample_size):
835
+ The height in pixels of the generated image.
836
+ width (`int`, *optional*, defaults to self.unet.config.sample_size):
837
+ The width in pixels of the generated image.
838
+ eta (`float`, *optional*, defaults to 0.0):
839
+ Corresponds to parameter eta (η) in the DDIM paper: https://huggingface.co/papers/2010.02502. Only
840
+ applies to [`schedulers.DDIMScheduler`], will be ignored for others.
841
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
842
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
843
+ to make generation deterministic.
844
+ latents (`torch.Tensor`, *optional*):
845
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
846
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
847
+ tensor will ge generated by sampling using the supplied random `generator`.
848
+ prompt_embeds (`torch.Tensor`, *optional*):
849
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
850
+ provided, text embeddings will be generated from `prompt` input argument.
851
+ prompt_attention_mask (`torch.Tensor`, *optional*): Pre-generated attention mask for text embeddings.
852
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
853
+ Pre-generated negative text embeddings. For PixArt-Sigma this negative prompt should be "". If not
854
+ provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
855
+ negative_prompt_attention_mask (`torch.Tensor`, *optional*):
856
+ Pre-generated attention mask for negative text embeddings.
857
+ output_type (`str`, *optional*, defaults to `"pil"`):
858
+ The output format of the generate image. Choose between
859
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
860
+ return_dict (`bool`, *optional*, defaults to `True`):
861
+ Whether or not to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
862
+ attention_kwargs:
863
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
864
+ `self.processor` in
865
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
866
+ clean_caption (`bool`, *optional*, defaults to `True`):
867
+ Whether or not to clean the caption before creating embeddings. Requires `beautifulsoup4` and `ftfy` to
868
+ be installed. If the dependencies are not installed, the embeddings will be created from the raw
869
+ prompt.
870
+ use_resolution_binning (`bool` defaults to `True`):
871
+ If set to `True`, the requested height and width are first mapped to the closest resolutions using
872
+ `ASPECT_RATIO_1024_BIN`. After the produced latents are decoded into images, they are resized back to
873
+ the requested resolution. Useful for generating non-square images.
874
+ callback_on_step_end (`Callable`, *optional*):
875
+ A function that calls at the end of each denoising steps during the inference. The function is called
876
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
877
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
878
+ `callback_on_step_end_tensor_inputs`.
879
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
880
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
881
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
882
+ `._callback_tensor_inputs` attribute of your pipeline class.
883
+ max_sequence_length (`int` defaults to `300`):
884
+ Maximum sequence length to use with the `prompt`.
885
+ complex_human_instruction (`List[str]`, *optional*):
886
+ Instructions for complex human attention:
887
+ https://github.com/NVlabs/Sana/blob/main/configs/sana_app_config/Sana_1600M_app.yaml#L55.
888
+
889
+ Examples:
890
+
891
+ Returns:
892
+ [`~pipelines.sana.pipeline_output.SanaPipelineOutput`] or `tuple`:
893
+ If `return_dict` is `True`, [`~pipelines.sana.pipeline_output.SanaPipelineOutput`] is returned,
894
+ otherwise a `tuple` is returned where the first element is a list with the generated images
895
+ """
896
+
897
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
898
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
899
+
900
+ # 1. Check inputs. Raise error if not correct
901
+ if use_resolution_binning:
902
+ if self.transformer.config.sample_size == 128:
903
+ aspect_ratio_bin = ASPECT_RATIO_4096_BIN
904
+ elif self.transformer.config.sample_size == 64:
905
+ aspect_ratio_bin = ASPECT_RATIO_2048_BIN
906
+ elif self.transformer.config.sample_size == 32:
907
+ aspect_ratio_bin = ASPECT_RATIO_1024_BIN
908
+ elif self.transformer.config.sample_size == 16:
909
+ aspect_ratio_bin = ASPECT_RATIO_512_BIN
910
+ else:
911
+ raise ValueError("Invalid sample size")
912
+ orig_height, orig_width = height, width
913
+ height, width = self.image_processor.classify_height_width_bin(height, width, ratios=aspect_ratio_bin)
914
+
915
+ self.check_inputs(
916
+ prompt,
917
+ height,
918
+ width,
919
+ callback_on_step_end_tensor_inputs,
920
+ negative_prompt,
921
+ prompt_embeds,
922
+ negative_prompt_embeds,
923
+ prompt_attention_mask,
924
+ negative_prompt_attention_mask,
925
+ )
926
+
927
+ self._guidance_scale = guidance_scale
928
+ self._attention_kwargs = attention_kwargs
929
+ self._interrupt = False
930
+
931
+ # 2. Default height and width to transformer
932
+ if prompt is not None and isinstance(prompt, str):
933
+ batch_size = 1
934
+ elif prompt is not None and isinstance(prompt, list):
935
+ batch_size = len(prompt)
936
+ else:
937
+ batch_size = prompt_embeds.shape[0]
938
+
939
+ device = self._execution_device
940
+ lora_scale = self.attention_kwargs.get("scale", None) if self.attention_kwargs is not None else None
941
+
942
+ # 3. Encode input prompt
943
+ (
944
+ prompt_embeds,
945
+ prompt_attention_mask,
946
+ negative_prompt_embeds,
947
+ negative_prompt_attention_mask,
948
+ ) = self.encode_prompt(
949
+ prompt,
950
+ self.do_classifier_free_guidance,
951
+ negative_prompt=negative_prompt,
952
+ num_images_per_prompt=num_images_per_prompt,
953
+ device=device,
954
+ prompt_embeds=prompt_embeds,
955
+ negative_prompt_embeds=negative_prompt_embeds,
956
+ prompt_attention_mask=prompt_attention_mask,
957
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
958
+ clean_caption=clean_caption,
959
+ max_sequence_length=max_sequence_length,
960
+ complex_human_instruction=complex_human_instruction,
961
+ lora_scale=lora_scale,
962
+ )
963
+ if self.do_classifier_free_guidance:
964
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
965
+ prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)
966
+
967
+ # 4. Prepare control image
968
+ if isinstance(self.controlnet, SanaControlNetModel):
969
+ control_image = self.prepare_image(
970
+ image=control_image,
971
+ width=width,
972
+ height=height,
973
+ batch_size=batch_size * num_images_per_prompt,
974
+ num_images_per_prompt=num_images_per_prompt,
975
+ device=device,
976
+ dtype=self.vae.dtype,
977
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
978
+ guess_mode=False,
979
+ )
980
+ height, width = control_image.shape[-2:]
981
+
982
+ control_image = self.vae.encode(control_image).latent
983
+ control_image = control_image * self.vae.config.scaling_factor
984
+ else:
985
+ raise ValueError("`controlnet` must be of type `SanaControlNetModel`.")
986
+
987
+ # 5. Prepare timesteps
988
+ timesteps, num_inference_steps = retrieve_timesteps(
989
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
990
+ )
991
+
992
+ # 6. Prepare latents.
993
+ latent_channels = self.transformer.config.in_channels
994
+ latents = self.prepare_latents(
995
+ batch_size * num_images_per_prompt,
996
+ latent_channels,
997
+ height,
998
+ width,
999
+ torch.float32,
1000
+ device,
1001
+ generator,
1002
+ latents,
1003
+ )
1004
+
1005
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1006
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1007
+
1008
+ # 8. Denoising loop
1009
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1010
+ self._num_timesteps = len(timesteps)
1011
+
1012
+ controlnet_dtype = self.controlnet.dtype
1013
+ transformer_dtype = self.transformer.dtype
1014
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1015
+ for i, t in enumerate(timesteps):
1016
+ if self.interrupt:
1017
+ continue
1018
+
1019
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1020
+
1021
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
1022
+ timestep = t.expand(latent_model_input.shape[0])
1023
+
1024
+ # controlnet(s) inference
1025
+ controlnet_block_samples = self.controlnet(
1026
+ latent_model_input.to(dtype=controlnet_dtype),
1027
+ encoder_hidden_states=prompt_embeds.to(dtype=controlnet_dtype),
1028
+ encoder_attention_mask=prompt_attention_mask,
1029
+ timestep=timestep,
1030
+ return_dict=False,
1031
+ attention_kwargs=self.attention_kwargs,
1032
+ controlnet_cond=control_image,
1033
+ conditioning_scale=controlnet_conditioning_scale,
1034
+ )[0]
1035
+
1036
+ # predict noise model_output
1037
+ noise_pred = self.transformer(
1038
+ latent_model_input.to(dtype=transformer_dtype),
1039
+ encoder_hidden_states=prompt_embeds.to(dtype=transformer_dtype),
1040
+ encoder_attention_mask=prompt_attention_mask,
1041
+ timestep=timestep,
1042
+ return_dict=False,
1043
+ attention_kwargs=self.attention_kwargs,
1044
+ controlnet_block_samples=tuple(t.to(dtype=transformer_dtype) for t in controlnet_block_samples),
1045
+ )[0]
1046
+ noise_pred = noise_pred.float()
1047
+
1048
+ # perform guidance
1049
+ if self.do_classifier_free_guidance:
1050
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1051
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1052
+
1053
+ # learned sigma
1054
+ if self.transformer.config.out_channels // 2 == latent_channels:
1055
+ noise_pred = noise_pred.chunk(2, dim=1)[0]
1056
+
1057
+ # compute previous image: x_t -> x_t-1
1058
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1059
+
1060
+ if callback_on_step_end is not None:
1061
+ callback_kwargs = {}
1062
+ for k in callback_on_step_end_tensor_inputs:
1063
+ callback_kwargs[k] = locals()[k]
1064
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1065
+
1066
+ latents = callback_outputs.pop("latents", latents)
1067
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1068
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1069
+
1070
+ # call the callback, if provided
1071
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1072
+ progress_bar.update()
1073
+
1074
+ if XLA_AVAILABLE:
1075
+ xm.mark_step()
1076
+
1077
+ if output_type == "latent":
1078
+ image = latents
1079
+ else:
1080
+ latents = latents.to(self.vae.dtype)
1081
+ torch_accelerator_module = getattr(torch, get_device(), torch.cuda)
1082
+ oom_error = (
1083
+ torch.OutOfMemoryError
1084
+ if is_torch_version(">=", "2.5.0")
1085
+ else torch_accelerator_module.OutOfMemoryError
1086
+ )
1087
+ try:
1088
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1089
+ except oom_error as e:
1090
+ warnings.warn(
1091
+ f"{e}. \n"
1092
+ f"Try to use VAE tiling for large images. For example: \n"
1093
+ f"pipe.vae.enable_tiling(tile_sample_min_width=512, tile_sample_min_height=512)"
1094
+ )
1095
+ if use_resolution_binning:
1096
+ image = self.image_processor.resize_and_crop_tensor(image, orig_width, orig_height)
1097
+
1098
+ image = self.image_processor.postprocess(image, output_type=output_type)
1099
+
1100
+ # Offload all models
1101
+ self.maybe_free_model_hooks()
1102
+
1103
+ if not return_dict:
1104
+ return (image,)
1105
+
1106
+ return SanaPipelineOutput(images=image)