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,262 @@
1
+ # Copyright 2025 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 TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
17
+
18
+ import torch
19
+
20
+ from ..configuration_utils import register_to_config
21
+ from ..hooks import HookRegistry, LayerSkipConfig
22
+ from ..hooks.layer_skip import _apply_layer_skip_hook
23
+ from .guider_utils import BaseGuidance, rescale_noise_cfg
24
+
25
+
26
+ if TYPE_CHECKING:
27
+ from ..modular_pipelines.modular_pipeline import BlockState
28
+
29
+
30
+ class SkipLayerGuidance(BaseGuidance):
31
+ """
32
+ Skip Layer Guidance (SLG): https://github.com/Stability-AI/sd3.5
33
+
34
+ Spatio-Temporal Guidance (STG): https://huggingface.co/papers/2411.18664
35
+
36
+ SLG was introduced by StabilityAI for improving structure and anotomy coherence in generated images. It works by
37
+ skipping the forward pass of specified transformer blocks during the denoising process on an additional conditional
38
+ batch of data, apart from the conditional and unconditional batches already used in CFG
39
+ ([~guiders.classifier_free_guidance.ClassifierFreeGuidance]), and then scaling and shifting the CFG predictions
40
+ based on the difference between conditional without skipping and conditional with skipping predictions.
41
+
42
+ The intution behind SLG can be thought of as moving the CFG predicted distribution estimates further away from
43
+ worse versions of the conditional distribution estimates (because skipping layers is equivalent to using a worse
44
+ version of the model for the conditional prediction).
45
+
46
+ STG is an improvement and follow-up work combining ideas from SLG, PAG and similar techniques for improving
47
+ generation quality in video diffusion models.
48
+
49
+ Additional reading:
50
+ - [Guiding a Diffusion Model with a Bad Version of Itself](https://huggingface.co/papers/2406.02507)
51
+
52
+ The values for `skip_layer_guidance_scale`, `skip_layer_guidance_start`, and `skip_layer_guidance_stop` are
53
+ defaulted to the recommendations by StabilityAI for Stable Diffusion 3.5 Medium.
54
+
55
+ Args:
56
+ guidance_scale (`float`, defaults to `7.5`):
57
+ The scale parameter for classifier-free guidance. Higher values result in stronger conditioning on the text
58
+ prompt, while lower values allow for more freedom in generation. Higher values may lead to saturation and
59
+ deterioration of image quality.
60
+ skip_layer_guidance_scale (`float`, defaults to `2.8`):
61
+ The scale parameter for skip layer guidance. Anatomy and structure coherence may improve with higher
62
+ values, but it may also lead to overexposure and saturation.
63
+ skip_layer_guidance_start (`float`, defaults to `0.01`):
64
+ The fraction of the total number of denoising steps after which skip layer guidance starts.
65
+ skip_layer_guidance_stop (`float`, defaults to `0.2`):
66
+ The fraction of the total number of denoising steps after which skip layer guidance stops.
67
+ skip_layer_guidance_layers (`int` or `List[int]`, *optional*):
68
+ The layer indices to apply skip layer guidance to. Can be a single integer or a list of integers. If not
69
+ provided, `skip_layer_config` must be provided. The recommended values are `[7, 8, 9]` for Stable Diffusion
70
+ 3.5 Medium.
71
+ skip_layer_config (`LayerSkipConfig` or `List[LayerSkipConfig]`, *optional*):
72
+ The configuration for the skip layer guidance. Can be a single `LayerSkipConfig` or a list of
73
+ `LayerSkipConfig`. If not provided, `skip_layer_guidance_layers` must be provided.
74
+ guidance_rescale (`float`, defaults to `0.0`):
75
+ The rescale factor applied to the noise predictions. This is used to improve image quality and fix
76
+ overexposure. Based on Section 3.4 from [Common Diffusion Noise Schedules and Sample Steps are
77
+ Flawed](https://huggingface.co/papers/2305.08891).
78
+ use_original_formulation (`bool`, defaults to `False`):
79
+ Whether to use the original formulation of classifier-free guidance as proposed in the paper. By default,
80
+ we use the diffusers-native implementation that has been in the codebase for a long time. See
81
+ [~guiders.classifier_free_guidance.ClassifierFreeGuidance] for more details.
82
+ start (`float`, defaults to `0.01`):
83
+ The fraction of the total number of denoising steps after which guidance starts.
84
+ stop (`float`, defaults to `0.2`):
85
+ The fraction of the total number of denoising steps after which guidance stops.
86
+ """
87
+
88
+ _input_predictions = ["pred_cond", "pred_uncond", "pred_cond_skip"]
89
+
90
+ @register_to_config
91
+ def __init__(
92
+ self,
93
+ guidance_scale: float = 7.5,
94
+ skip_layer_guidance_scale: float = 2.8,
95
+ skip_layer_guidance_start: float = 0.01,
96
+ skip_layer_guidance_stop: float = 0.2,
97
+ skip_layer_guidance_layers: Optional[Union[int, List[int]]] = None,
98
+ skip_layer_config: Union[LayerSkipConfig, List[LayerSkipConfig], Dict[str, Any]] = None,
99
+ guidance_rescale: float = 0.0,
100
+ use_original_formulation: bool = False,
101
+ start: float = 0.0,
102
+ stop: float = 1.0,
103
+ ):
104
+ super().__init__(start, stop)
105
+
106
+ self.guidance_scale = guidance_scale
107
+ self.skip_layer_guidance_scale = skip_layer_guidance_scale
108
+ self.skip_layer_guidance_start = skip_layer_guidance_start
109
+ self.skip_layer_guidance_stop = skip_layer_guidance_stop
110
+ self.guidance_rescale = guidance_rescale
111
+ self.use_original_formulation = use_original_formulation
112
+
113
+ if not (0.0 <= skip_layer_guidance_start < 1.0):
114
+ raise ValueError(
115
+ f"Expected `skip_layer_guidance_start` to be between 0.0 and 1.0, but got {skip_layer_guidance_start}."
116
+ )
117
+ if not (skip_layer_guidance_start <= skip_layer_guidance_stop <= 1.0):
118
+ raise ValueError(
119
+ f"Expected `skip_layer_guidance_stop` to be between 0.0 and 1.0, but got {skip_layer_guidance_stop}."
120
+ )
121
+
122
+ if skip_layer_guidance_layers is None and skip_layer_config is None:
123
+ raise ValueError(
124
+ "Either `skip_layer_guidance_layers` or `skip_layer_config` must be provided to enable Skip Layer Guidance."
125
+ )
126
+ if skip_layer_guidance_layers is not None and skip_layer_config is not None:
127
+ raise ValueError("Only one of `skip_layer_guidance_layers` or `skip_layer_config` can be provided.")
128
+
129
+ if skip_layer_guidance_layers is not None:
130
+ if isinstance(skip_layer_guidance_layers, int):
131
+ skip_layer_guidance_layers = [skip_layer_guidance_layers]
132
+ if not isinstance(skip_layer_guidance_layers, list):
133
+ raise ValueError(
134
+ f"Expected `skip_layer_guidance_layers` to be an int or a list of ints, but got {type(skip_layer_guidance_layers)}."
135
+ )
136
+ skip_layer_config = [LayerSkipConfig(layer, fqn="auto") for layer in skip_layer_guidance_layers]
137
+
138
+ if isinstance(skip_layer_config, dict):
139
+ skip_layer_config = LayerSkipConfig.from_dict(skip_layer_config)
140
+
141
+ if isinstance(skip_layer_config, LayerSkipConfig):
142
+ skip_layer_config = [skip_layer_config]
143
+
144
+ if not isinstance(skip_layer_config, list):
145
+ raise ValueError(
146
+ f"Expected `skip_layer_config` to be a LayerSkipConfig or a list of LayerSkipConfig, but got {type(skip_layer_config)}."
147
+ )
148
+ elif isinstance(next(iter(skip_layer_config), None), dict):
149
+ skip_layer_config = [LayerSkipConfig.from_dict(config) for config in skip_layer_config]
150
+
151
+ self.skip_layer_config = skip_layer_config
152
+ self._skip_layer_hook_names = [f"SkipLayerGuidance_{i}" for i in range(len(self.skip_layer_config))]
153
+
154
+ def prepare_models(self, denoiser: torch.nn.Module) -> None:
155
+ self._count_prepared += 1
156
+ if self._is_slg_enabled() and self.is_conditional and self._count_prepared > 1:
157
+ for name, config in zip(self._skip_layer_hook_names, self.skip_layer_config):
158
+ _apply_layer_skip_hook(denoiser, config, name=name)
159
+
160
+ def cleanup_models(self, denoiser: torch.nn.Module) -> None:
161
+ if self._is_slg_enabled() and self.is_conditional and self._count_prepared > 1:
162
+ registry = HookRegistry.check_if_exists_or_initialize(denoiser)
163
+ # Remove the hooks after inference
164
+ for hook_name in self._skip_layer_hook_names:
165
+ registry.remove_hook(hook_name, recurse=True)
166
+
167
+ def prepare_inputs(
168
+ self, data: "BlockState", input_fields: Optional[Dict[str, Union[str, Tuple[str, str]]]] = None
169
+ ) -> List["BlockState"]:
170
+ if input_fields is None:
171
+ input_fields = self._input_fields
172
+
173
+ if self.num_conditions == 1:
174
+ tuple_indices = [0]
175
+ input_predictions = ["pred_cond"]
176
+ elif self.num_conditions == 2:
177
+ tuple_indices = [0, 1]
178
+ input_predictions = (
179
+ ["pred_cond", "pred_uncond"] if self._is_cfg_enabled() else ["pred_cond", "pred_cond_skip"]
180
+ )
181
+ else:
182
+ tuple_indices = [0, 1, 0]
183
+ input_predictions = ["pred_cond", "pred_uncond", "pred_cond_skip"]
184
+ data_batches = []
185
+ for i in range(self.num_conditions):
186
+ data_batch = self._prepare_batch(input_fields, data, tuple_indices[i], input_predictions[i])
187
+ data_batches.append(data_batch)
188
+ return data_batches
189
+
190
+ def forward(
191
+ self,
192
+ pred_cond: torch.Tensor,
193
+ pred_uncond: Optional[torch.Tensor] = None,
194
+ pred_cond_skip: Optional[torch.Tensor] = None,
195
+ ) -> torch.Tensor:
196
+ pred = None
197
+
198
+ if not self._is_cfg_enabled() and not self._is_slg_enabled():
199
+ pred = pred_cond
200
+ elif not self._is_cfg_enabled():
201
+ shift = pred_cond - pred_cond_skip
202
+ pred = pred_cond if self.use_original_formulation else pred_cond_skip
203
+ pred = pred + self.skip_layer_guidance_scale * shift
204
+ elif not self._is_slg_enabled():
205
+ shift = pred_cond - pred_uncond
206
+ pred = pred_cond if self.use_original_formulation else pred_uncond
207
+ pred = pred + self.guidance_scale * shift
208
+ else:
209
+ shift = pred_cond - pred_uncond
210
+ shift_skip = pred_cond - pred_cond_skip
211
+ pred = pred_cond if self.use_original_formulation else pred_uncond
212
+ pred = pred + self.guidance_scale * shift + self.skip_layer_guidance_scale * shift_skip
213
+
214
+ if self.guidance_rescale > 0.0:
215
+ pred = rescale_noise_cfg(pred, pred_cond, self.guidance_rescale)
216
+
217
+ return pred, {}
218
+
219
+ @property
220
+ def is_conditional(self) -> bool:
221
+ return self._count_prepared == 1 or self._count_prepared == 3
222
+
223
+ @property
224
+ def num_conditions(self) -> int:
225
+ num_conditions = 1
226
+ if self._is_cfg_enabled():
227
+ num_conditions += 1
228
+ if self._is_slg_enabled():
229
+ num_conditions += 1
230
+ return num_conditions
231
+
232
+ def _is_cfg_enabled(self) -> bool:
233
+ if not self._enabled:
234
+ return False
235
+
236
+ is_within_range = True
237
+ if self._num_inference_steps is not None:
238
+ skip_start_step = int(self._start * self._num_inference_steps)
239
+ skip_stop_step = int(self._stop * self._num_inference_steps)
240
+ is_within_range = skip_start_step <= self._step < skip_stop_step
241
+
242
+ is_close = False
243
+ if self.use_original_formulation:
244
+ is_close = math.isclose(self.guidance_scale, 0.0)
245
+ else:
246
+ is_close = math.isclose(self.guidance_scale, 1.0)
247
+
248
+ return is_within_range and not is_close
249
+
250
+ def _is_slg_enabled(self) -> bool:
251
+ if not self._enabled:
252
+ return False
253
+
254
+ is_within_range = True
255
+ if self._num_inference_steps is not None:
256
+ skip_start_step = int(self.skip_layer_guidance_start * self._num_inference_steps)
257
+ skip_stop_step = int(self.skip_layer_guidance_stop * self._num_inference_steps)
258
+ is_within_range = skip_start_step < self._step < skip_stop_step
259
+
260
+ is_zero = math.isclose(self.skip_layer_guidance_scale, 0.0)
261
+
262
+ return is_within_range and not is_zero
@@ -0,0 +1,251 @@
1
+ # Copyright 2025 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 TYPE_CHECKING, Dict, List, Optional, Tuple, Union
17
+
18
+ import torch
19
+
20
+ from ..configuration_utils import register_to_config
21
+ from ..hooks import HookRegistry
22
+ from ..hooks.smoothed_energy_guidance_utils import SmoothedEnergyGuidanceConfig, _apply_smoothed_energy_guidance_hook
23
+ from .guider_utils import BaseGuidance, rescale_noise_cfg
24
+
25
+
26
+ if TYPE_CHECKING:
27
+ from ..modular_pipelines.modular_pipeline import BlockState
28
+
29
+
30
+ class SmoothedEnergyGuidance(BaseGuidance):
31
+ """
32
+ Smoothed Energy Guidance (SEG): https://huggingface.co/papers/2408.00760
33
+
34
+ SEG is only supported as an experimental prototype feature for now, so the implementation may be modified in the
35
+ future without warning or guarantee of reproducibility. This implementation assumes:
36
+ - Generated images are square (height == width)
37
+ - The model does not combine different modalities together (e.g., text and image latent streams are not combined
38
+ together such as Flux)
39
+
40
+ Args:
41
+ guidance_scale (`float`, defaults to `7.5`):
42
+ The scale parameter for classifier-free guidance. Higher values result in stronger conditioning on the text
43
+ prompt, while lower values allow for more freedom in generation. Higher values may lead to saturation and
44
+ deterioration of image quality.
45
+ seg_guidance_scale (`float`, defaults to `3.0`):
46
+ The scale parameter for smoothed energy guidance. Anatomy and structure coherence may improve with higher
47
+ values, but it may also lead to overexposure and saturation.
48
+ seg_blur_sigma (`float`, defaults to `9999999.0`):
49
+ The amount by which we blur the attention weights. Setting this value greater than 9999.0 results in
50
+ infinite blur, which means uniform queries. Controlling it exponentially is empirically effective.
51
+ seg_blur_threshold_inf (`float`, defaults to `9999.0`):
52
+ The threshold above which the blur is considered infinite.
53
+ seg_guidance_start (`float`, defaults to `0.0`):
54
+ The fraction of the total number of denoising steps after which smoothed energy guidance starts.
55
+ seg_guidance_stop (`float`, defaults to `1.0`):
56
+ The fraction of the total number of denoising steps after which smoothed energy guidance stops.
57
+ seg_guidance_layers (`int` or `List[int]`, *optional*):
58
+ The layer indices to apply smoothed energy guidance to. Can be a single integer or a list of integers. If
59
+ not provided, `seg_guidance_config` must be provided. The recommended values are `[7, 8, 9]` for Stable
60
+ Diffusion 3.5 Medium.
61
+ seg_guidance_config (`SmoothedEnergyGuidanceConfig` or `List[SmoothedEnergyGuidanceConfig]`, *optional*):
62
+ The configuration for the smoothed energy layer guidance. Can be a single `SmoothedEnergyGuidanceConfig` or
63
+ a list of `SmoothedEnergyGuidanceConfig`. If not provided, `seg_guidance_layers` must be provided.
64
+ guidance_rescale (`float`, defaults to `0.0`):
65
+ The rescale factor applied to the noise predictions. This is used to improve image quality and fix
66
+ overexposure. Based on Section 3.4 from [Common Diffusion Noise Schedules and Sample Steps are
67
+ Flawed](https://huggingface.co/papers/2305.08891).
68
+ use_original_formulation (`bool`, defaults to `False`):
69
+ Whether to use the original formulation of classifier-free guidance as proposed in the paper. By default,
70
+ we use the diffusers-native implementation that has been in the codebase for a long time. See
71
+ [~guiders.classifier_free_guidance.ClassifierFreeGuidance] for more details.
72
+ start (`float`, defaults to `0.01`):
73
+ The fraction of the total number of denoising steps after which guidance starts.
74
+ stop (`float`, defaults to `0.2`):
75
+ The fraction of the total number of denoising steps after which guidance stops.
76
+ """
77
+
78
+ _input_predictions = ["pred_cond", "pred_uncond", "pred_cond_seg"]
79
+
80
+ @register_to_config
81
+ def __init__(
82
+ self,
83
+ guidance_scale: float = 7.5,
84
+ seg_guidance_scale: float = 2.8,
85
+ seg_blur_sigma: float = 9999999.0,
86
+ seg_blur_threshold_inf: float = 9999.0,
87
+ seg_guidance_start: float = 0.0,
88
+ seg_guidance_stop: float = 1.0,
89
+ seg_guidance_layers: Optional[Union[int, List[int]]] = None,
90
+ seg_guidance_config: Union[SmoothedEnergyGuidanceConfig, List[SmoothedEnergyGuidanceConfig]] = None,
91
+ guidance_rescale: float = 0.0,
92
+ use_original_formulation: bool = False,
93
+ start: float = 0.0,
94
+ stop: float = 1.0,
95
+ ):
96
+ super().__init__(start, stop)
97
+
98
+ self.guidance_scale = guidance_scale
99
+ self.seg_guidance_scale = seg_guidance_scale
100
+ self.seg_blur_sigma = seg_blur_sigma
101
+ self.seg_blur_threshold_inf = seg_blur_threshold_inf
102
+ self.seg_guidance_start = seg_guidance_start
103
+ self.seg_guidance_stop = seg_guidance_stop
104
+ self.guidance_rescale = guidance_rescale
105
+ self.use_original_formulation = use_original_formulation
106
+
107
+ if not (0.0 <= seg_guidance_start < 1.0):
108
+ raise ValueError(f"Expected `seg_guidance_start` to be between 0.0 and 1.0, but got {seg_guidance_start}.")
109
+ if not (seg_guidance_start <= seg_guidance_stop <= 1.0):
110
+ raise ValueError(f"Expected `seg_guidance_stop` to be between 0.0 and 1.0, but got {seg_guidance_stop}.")
111
+
112
+ if seg_guidance_layers is None and seg_guidance_config is None:
113
+ raise ValueError(
114
+ "Either `seg_guidance_layers` or `seg_guidance_config` must be provided to enable Smoothed Energy Guidance."
115
+ )
116
+ if seg_guidance_layers is not None and seg_guidance_config is not None:
117
+ raise ValueError("Only one of `seg_guidance_layers` or `seg_guidance_config` can be provided.")
118
+
119
+ if seg_guidance_layers is not None:
120
+ if isinstance(seg_guidance_layers, int):
121
+ seg_guidance_layers = [seg_guidance_layers]
122
+ if not isinstance(seg_guidance_layers, list):
123
+ raise ValueError(
124
+ f"Expected `seg_guidance_layers` to be an int or a list of ints, but got {type(seg_guidance_layers)}."
125
+ )
126
+ seg_guidance_config = [SmoothedEnergyGuidanceConfig(layer, fqn="auto") for layer in seg_guidance_layers]
127
+
128
+ if isinstance(seg_guidance_config, dict):
129
+ seg_guidance_config = SmoothedEnergyGuidanceConfig.from_dict(seg_guidance_config)
130
+
131
+ if isinstance(seg_guidance_config, SmoothedEnergyGuidanceConfig):
132
+ seg_guidance_config = [seg_guidance_config]
133
+
134
+ if not isinstance(seg_guidance_config, list):
135
+ raise ValueError(
136
+ f"Expected `seg_guidance_config` to be a SmoothedEnergyGuidanceConfig or a list of SmoothedEnergyGuidanceConfig, but got {type(seg_guidance_config)}."
137
+ )
138
+ elif isinstance(next(iter(seg_guidance_config), None), dict):
139
+ seg_guidance_config = [SmoothedEnergyGuidanceConfig.from_dict(config) for config in seg_guidance_config]
140
+
141
+ self.seg_guidance_config = seg_guidance_config
142
+ self._seg_layer_hook_names = [f"SmoothedEnergyGuidance_{i}" for i in range(len(self.seg_guidance_config))]
143
+
144
+ def prepare_models(self, denoiser: torch.nn.Module) -> None:
145
+ if self._is_seg_enabled() and self.is_conditional and self._count_prepared > 1:
146
+ for name, config in zip(self._seg_layer_hook_names, self.seg_guidance_config):
147
+ _apply_smoothed_energy_guidance_hook(denoiser, config, self.seg_blur_sigma, name=name)
148
+
149
+ def cleanup_models(self, denoiser: torch.nn.Module):
150
+ if self._is_seg_enabled() and self.is_conditional and self._count_prepared > 1:
151
+ registry = HookRegistry.check_if_exists_or_initialize(denoiser)
152
+ # Remove the hooks after inference
153
+ for hook_name in self._seg_layer_hook_names:
154
+ registry.remove_hook(hook_name, recurse=True)
155
+
156
+ def prepare_inputs(
157
+ self, data: "BlockState", input_fields: Optional[Dict[str, Union[str, Tuple[str, str]]]] = None
158
+ ) -> List["BlockState"]:
159
+ if input_fields is None:
160
+ input_fields = self._input_fields
161
+
162
+ if self.num_conditions == 1:
163
+ tuple_indices = [0]
164
+ input_predictions = ["pred_cond"]
165
+ elif self.num_conditions == 2:
166
+ tuple_indices = [0, 1]
167
+ input_predictions = (
168
+ ["pred_cond", "pred_uncond"] if self._is_cfg_enabled() else ["pred_cond", "pred_cond_seg"]
169
+ )
170
+ else:
171
+ tuple_indices = [0, 1, 0]
172
+ input_predictions = ["pred_cond", "pred_uncond", "pred_cond_seg"]
173
+ data_batches = []
174
+ for i in range(self.num_conditions):
175
+ data_batch = self._prepare_batch(input_fields, data, tuple_indices[i], input_predictions[i])
176
+ data_batches.append(data_batch)
177
+ return data_batches
178
+
179
+ def forward(
180
+ self,
181
+ pred_cond: torch.Tensor,
182
+ pred_uncond: Optional[torch.Tensor] = None,
183
+ pred_cond_seg: Optional[torch.Tensor] = None,
184
+ ) -> torch.Tensor:
185
+ pred = None
186
+
187
+ if not self._is_cfg_enabled() and not self._is_seg_enabled():
188
+ pred = pred_cond
189
+ elif not self._is_cfg_enabled():
190
+ shift = pred_cond - pred_cond_seg
191
+ pred = pred_cond if self.use_original_formulation else pred_cond_seg
192
+ pred = pred + self.seg_guidance_scale * shift
193
+ elif not self._is_seg_enabled():
194
+ shift = pred_cond - pred_uncond
195
+ pred = pred_cond if self.use_original_formulation else pred_uncond
196
+ pred = pred + self.guidance_scale * shift
197
+ else:
198
+ shift = pred_cond - pred_uncond
199
+ shift_seg = pred_cond - pred_cond_seg
200
+ pred = pred_cond if self.use_original_formulation else pred_uncond
201
+ pred = pred + self.guidance_scale * shift + self.seg_guidance_scale * shift_seg
202
+
203
+ if self.guidance_rescale > 0.0:
204
+ pred = rescale_noise_cfg(pred, pred_cond, self.guidance_rescale)
205
+
206
+ return pred, {}
207
+
208
+ @property
209
+ def is_conditional(self) -> bool:
210
+ return self._count_prepared == 1 or self._count_prepared == 3
211
+
212
+ @property
213
+ def num_conditions(self) -> int:
214
+ num_conditions = 1
215
+ if self._is_cfg_enabled():
216
+ num_conditions += 1
217
+ if self._is_seg_enabled():
218
+ num_conditions += 1
219
+ return num_conditions
220
+
221
+ def _is_cfg_enabled(self) -> bool:
222
+ if not self._enabled:
223
+ return False
224
+
225
+ is_within_range = True
226
+ if self._num_inference_steps is not None:
227
+ skip_start_step = int(self._start * self._num_inference_steps)
228
+ skip_stop_step = int(self._stop * self._num_inference_steps)
229
+ is_within_range = skip_start_step <= self._step < skip_stop_step
230
+
231
+ is_close = False
232
+ if self.use_original_formulation:
233
+ is_close = math.isclose(self.guidance_scale, 0.0)
234
+ else:
235
+ is_close = math.isclose(self.guidance_scale, 1.0)
236
+
237
+ return is_within_range and not is_close
238
+
239
+ def _is_seg_enabled(self) -> bool:
240
+ if not self._enabled:
241
+ return False
242
+
243
+ is_within_range = True
244
+ if self._num_inference_steps is not None:
245
+ skip_start_step = int(self.seg_guidance_start * self._num_inference_steps)
246
+ skip_stop_step = int(self.seg_guidance_stop * self._num_inference_steps)
247
+ is_within_range = skip_start_step < self._step < skip_stop_step
248
+
249
+ is_zero = math.isclose(self.seg_guidance_scale, 0.0)
250
+
251
+ return is_within_range and not is_zero
@@ -0,0 +1,143 @@
1
+ # Copyright 2025 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 TYPE_CHECKING, Dict, List, Optional, Tuple, Union
17
+
18
+ import torch
19
+
20
+ from ..configuration_utils import register_to_config
21
+ from .guider_utils import BaseGuidance, rescale_noise_cfg
22
+
23
+
24
+ if TYPE_CHECKING:
25
+ from ..modular_pipelines.modular_pipeline import BlockState
26
+
27
+
28
+ class TangentialClassifierFreeGuidance(BaseGuidance):
29
+ """
30
+ Tangential Classifier Free Guidance (TCFG): https://huggingface.co/papers/2503.18137
31
+
32
+ Args:
33
+ guidance_scale (`float`, defaults to `7.5`):
34
+ The scale parameter for classifier-free guidance. Higher values result in stronger conditioning on the text
35
+ prompt, while lower values allow for more freedom in generation. Higher values may lead to saturation and
36
+ deterioration of image quality.
37
+ guidance_rescale (`float`, defaults to `0.0`):
38
+ The rescale factor applied to the noise predictions. This is used to improve image quality and fix
39
+ overexposure. Based on Section 3.4 from [Common Diffusion Noise Schedules and Sample Steps are
40
+ Flawed](https://huggingface.co/papers/2305.08891).
41
+ use_original_formulation (`bool`, defaults to `False`):
42
+ Whether to use the original formulation of classifier-free guidance as proposed in the paper. By default,
43
+ we use the diffusers-native implementation that has been in the codebase for a long time. See
44
+ [~guiders.classifier_free_guidance.ClassifierFreeGuidance] for more details.
45
+ start (`float`, defaults to `0.0`):
46
+ The fraction of the total number of denoising steps after which guidance starts.
47
+ stop (`float`, defaults to `1.0`):
48
+ The fraction of the total number of denoising steps after which guidance stops.
49
+ """
50
+
51
+ _input_predictions = ["pred_cond", "pred_uncond"]
52
+
53
+ @register_to_config
54
+ def __init__(
55
+ self,
56
+ guidance_scale: float = 7.5,
57
+ guidance_rescale: float = 0.0,
58
+ use_original_formulation: bool = False,
59
+ start: float = 0.0,
60
+ stop: float = 1.0,
61
+ ):
62
+ super().__init__(start, stop)
63
+
64
+ self.guidance_scale = guidance_scale
65
+ self.guidance_rescale = guidance_rescale
66
+ self.use_original_formulation = use_original_formulation
67
+
68
+ def prepare_inputs(
69
+ self, data: "BlockState", input_fields: Optional[Dict[str, Union[str, Tuple[str, str]]]] = None
70
+ ) -> List["BlockState"]:
71
+ if input_fields is None:
72
+ input_fields = self._input_fields
73
+
74
+ tuple_indices = [0] if self.num_conditions == 1 else [0, 1]
75
+ data_batches = []
76
+ for i in range(self.num_conditions):
77
+ data_batch = self._prepare_batch(input_fields, data, tuple_indices[i], self._input_predictions[i])
78
+ data_batches.append(data_batch)
79
+ return data_batches
80
+
81
+ def forward(self, pred_cond: torch.Tensor, pred_uncond: Optional[torch.Tensor] = None) -> torch.Tensor:
82
+ pred = None
83
+
84
+ if not self._is_tcfg_enabled():
85
+ pred = pred_cond
86
+ else:
87
+ pred = normalized_guidance(pred_cond, pred_uncond, self.guidance_scale, self.use_original_formulation)
88
+
89
+ if self.guidance_rescale > 0.0:
90
+ pred = rescale_noise_cfg(pred, pred_cond, self.guidance_rescale)
91
+
92
+ return pred, {}
93
+
94
+ @property
95
+ def is_conditional(self) -> bool:
96
+ return self._num_outputs_prepared == 1
97
+
98
+ @property
99
+ def num_conditions(self) -> int:
100
+ num_conditions = 1
101
+ if self._is_tcfg_enabled():
102
+ num_conditions += 1
103
+ return num_conditions
104
+
105
+ def _is_tcfg_enabled(self) -> bool:
106
+ if not self._enabled:
107
+ return False
108
+
109
+ is_within_range = True
110
+ if self._num_inference_steps is not None:
111
+ skip_start_step = int(self._start * self._num_inference_steps)
112
+ skip_stop_step = int(self._stop * self._num_inference_steps)
113
+ is_within_range = skip_start_step <= self._step < skip_stop_step
114
+
115
+ is_close = False
116
+ if self.use_original_formulation:
117
+ is_close = math.isclose(self.guidance_scale, 0.0)
118
+ else:
119
+ is_close = math.isclose(self.guidance_scale, 1.0)
120
+
121
+ return is_within_range and not is_close
122
+
123
+
124
+ def normalized_guidance(
125
+ pred_cond: torch.Tensor, pred_uncond: torch.Tensor, guidance_scale: float, use_original_formulation: bool = False
126
+ ) -> torch.Tensor:
127
+ cond_dtype = pred_cond.dtype
128
+ preds = torch.stack([pred_cond, pred_uncond], dim=1).float()
129
+ preds = preds.flatten(2)
130
+ U, S, Vh = torch.linalg.svd(preds, full_matrices=False)
131
+ Vh_modified = Vh.clone()
132
+ Vh_modified[:, 1] = 0
133
+
134
+ uncond_flat = pred_uncond.reshape(pred_uncond.size(0), 1, -1).float()
135
+ x_Vh = torch.matmul(uncond_flat, Vh.transpose(-2, -1))
136
+ x_Vh_V = torch.matmul(x_Vh, Vh_modified)
137
+ pred_uncond = x_Vh_V.reshape(pred_uncond.shape).to(cond_dtype)
138
+
139
+ pred = pred_cond if use_original_formulation else pred_uncond
140
+ shift = pred_cond - pred_uncond
141
+ pred = pred + guidance_scale * shift
142
+
143
+ return pred
@@ -1,9 +1,26 @@
1
+ # Copyright 2024 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
+
1
15
  from ..utils import is_torch_available
2
16
 
3
17
 
4
18
  if is_torch_available():
5
19
  from .faster_cache import FasterCacheConfig, apply_faster_cache
20
+ from .first_block_cache import FirstBlockCacheConfig, apply_first_block_cache
6
21
  from .group_offloading import apply_group_offloading
7
22
  from .hooks import HookRegistry, ModelHook
23
+ from .layer_skip import LayerSkipConfig, apply_layer_skip
8
24
  from .layerwise_casting import apply_layerwise_casting, apply_layerwise_casting_hook
9
25
  from .pyramid_attention_broadcast import PyramidAttentionBroadcastConfig, apply_pyramid_attention_broadcast
26
+ from .smoothed_energy_guidance_utils import SmoothedEnergyGuidanceConfig