diffusers 0.34.0__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 (191) hide show
  1. diffusers/__init__.py +98 -1
  2. diffusers/callbacks.py +35 -0
  3. diffusers/commands/custom_blocks.py +134 -0
  4. diffusers/commands/diffusers_cli.py +2 -0
  5. diffusers/commands/fp16_safetensors.py +1 -1
  6. diffusers/configuration_utils.py +11 -2
  7. diffusers/dependency_versions_table.py +3 -3
  8. diffusers/guiders/__init__.py +41 -0
  9. diffusers/guiders/adaptive_projected_guidance.py +188 -0
  10. diffusers/guiders/auto_guidance.py +190 -0
  11. diffusers/guiders/classifier_free_guidance.py +141 -0
  12. diffusers/guiders/classifier_free_zero_star_guidance.py +152 -0
  13. diffusers/guiders/frequency_decoupled_guidance.py +327 -0
  14. diffusers/guiders/guider_utils.py +309 -0
  15. diffusers/guiders/perturbed_attention_guidance.py +271 -0
  16. diffusers/guiders/skip_layer_guidance.py +262 -0
  17. diffusers/guiders/smoothed_energy_guidance.py +251 -0
  18. diffusers/guiders/tangential_classifier_free_guidance.py +143 -0
  19. diffusers/hooks/__init__.py +17 -0
  20. diffusers/hooks/_common.py +56 -0
  21. diffusers/hooks/_helpers.py +293 -0
  22. diffusers/hooks/faster_cache.py +7 -6
  23. diffusers/hooks/first_block_cache.py +259 -0
  24. diffusers/hooks/group_offloading.py +292 -286
  25. diffusers/hooks/hooks.py +56 -1
  26. diffusers/hooks/layer_skip.py +263 -0
  27. diffusers/hooks/layerwise_casting.py +2 -7
  28. diffusers/hooks/pyramid_attention_broadcast.py +14 -11
  29. diffusers/hooks/smoothed_energy_guidance_utils.py +167 -0
  30. diffusers/hooks/utils.py +43 -0
  31. diffusers/loaders/__init__.py +6 -0
  32. diffusers/loaders/ip_adapter.py +255 -4
  33. diffusers/loaders/lora_base.py +63 -30
  34. diffusers/loaders/lora_conversion_utils.py +434 -53
  35. diffusers/loaders/lora_pipeline.py +834 -37
  36. diffusers/loaders/peft.py +28 -5
  37. diffusers/loaders/single_file_model.py +44 -11
  38. diffusers/loaders/single_file_utils.py +170 -2
  39. diffusers/loaders/transformer_flux.py +9 -10
  40. diffusers/loaders/transformer_sd3.py +6 -1
  41. diffusers/loaders/unet.py +22 -5
  42. diffusers/loaders/unet_loader_utils.py +5 -2
  43. diffusers/models/__init__.py +8 -0
  44. diffusers/models/attention.py +484 -3
  45. diffusers/models/attention_dispatch.py +1218 -0
  46. diffusers/models/attention_processor.py +105 -663
  47. diffusers/models/auto_model.py +2 -2
  48. diffusers/models/autoencoders/__init__.py +1 -0
  49. diffusers/models/autoencoders/autoencoder_dc.py +14 -1
  50. diffusers/models/autoencoders/autoencoder_kl.py +1 -1
  51. diffusers/models/autoencoders/autoencoder_kl_cosmos.py +3 -1
  52. diffusers/models/autoencoders/autoencoder_kl_qwenimage.py +1070 -0
  53. diffusers/models/autoencoders/autoencoder_kl_wan.py +370 -40
  54. diffusers/models/cache_utils.py +31 -9
  55. diffusers/models/controlnets/controlnet_flux.py +5 -5
  56. diffusers/models/controlnets/controlnet_union.py +4 -4
  57. diffusers/models/embeddings.py +26 -34
  58. diffusers/models/model_loading_utils.py +233 -1
  59. diffusers/models/modeling_flax_utils.py +1 -2
  60. diffusers/models/modeling_utils.py +159 -94
  61. diffusers/models/transformers/__init__.py +2 -0
  62. diffusers/models/transformers/transformer_chroma.py +16 -117
  63. diffusers/models/transformers/transformer_cogview4.py +36 -2
  64. diffusers/models/transformers/transformer_cosmos.py +11 -4
  65. diffusers/models/transformers/transformer_flux.py +372 -132
  66. diffusers/models/transformers/transformer_hunyuan_video.py +6 -0
  67. diffusers/models/transformers/transformer_ltx.py +104 -23
  68. diffusers/models/transformers/transformer_qwenimage.py +645 -0
  69. diffusers/models/transformers/transformer_skyreels_v2.py +607 -0
  70. diffusers/models/transformers/transformer_wan.py +298 -85
  71. diffusers/models/transformers/transformer_wan_vace.py +15 -21
  72. diffusers/models/unets/unet_2d_condition.py +2 -1
  73. diffusers/modular_pipelines/__init__.py +83 -0
  74. diffusers/modular_pipelines/components_manager.py +1068 -0
  75. diffusers/modular_pipelines/flux/__init__.py +66 -0
  76. diffusers/modular_pipelines/flux/before_denoise.py +689 -0
  77. diffusers/modular_pipelines/flux/decoders.py +109 -0
  78. diffusers/modular_pipelines/flux/denoise.py +227 -0
  79. diffusers/modular_pipelines/flux/encoders.py +412 -0
  80. diffusers/modular_pipelines/flux/modular_blocks.py +181 -0
  81. diffusers/modular_pipelines/flux/modular_pipeline.py +59 -0
  82. diffusers/modular_pipelines/modular_pipeline.py +2446 -0
  83. diffusers/modular_pipelines/modular_pipeline_utils.py +672 -0
  84. diffusers/modular_pipelines/node_utils.py +665 -0
  85. diffusers/modular_pipelines/stable_diffusion_xl/__init__.py +77 -0
  86. diffusers/modular_pipelines/stable_diffusion_xl/before_denoise.py +1874 -0
  87. diffusers/modular_pipelines/stable_diffusion_xl/decoders.py +208 -0
  88. diffusers/modular_pipelines/stable_diffusion_xl/denoise.py +771 -0
  89. diffusers/modular_pipelines/stable_diffusion_xl/encoders.py +887 -0
  90. diffusers/modular_pipelines/stable_diffusion_xl/modular_blocks.py +380 -0
  91. diffusers/modular_pipelines/stable_diffusion_xl/modular_pipeline.py +365 -0
  92. diffusers/modular_pipelines/wan/__init__.py +66 -0
  93. diffusers/modular_pipelines/wan/before_denoise.py +365 -0
  94. diffusers/modular_pipelines/wan/decoders.py +105 -0
  95. diffusers/modular_pipelines/wan/denoise.py +261 -0
  96. diffusers/modular_pipelines/wan/encoders.py +242 -0
  97. diffusers/modular_pipelines/wan/modular_blocks.py +144 -0
  98. diffusers/modular_pipelines/wan/modular_pipeline.py +90 -0
  99. diffusers/pipelines/__init__.py +31 -0
  100. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +2 -3
  101. diffusers/pipelines/auto_pipeline.py +17 -13
  102. diffusers/pipelines/chroma/pipeline_chroma.py +5 -5
  103. diffusers/pipelines/chroma/pipeline_chroma_img2img.py +5 -5
  104. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +9 -8
  105. diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +9 -8
  106. diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +10 -9
  107. diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +9 -8
  108. diffusers/pipelines/cogview4/pipeline_cogview4.py +16 -15
  109. diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +3 -2
  110. diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +212 -93
  111. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +7 -3
  112. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +194 -92
  113. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +1 -1
  114. diffusers/pipelines/dit/pipeline_dit.py +3 -1
  115. diffusers/pipelines/flux/__init__.py +4 -0
  116. diffusers/pipelines/flux/pipeline_flux.py +34 -26
  117. diffusers/pipelines/flux/pipeline_flux_control.py +8 -8
  118. diffusers/pipelines/flux/pipeline_flux_control_img2img.py +1 -1
  119. diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +1 -1
  120. diffusers/pipelines/flux/pipeline_flux_controlnet.py +1 -1
  121. diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +1 -1
  122. diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +1 -1
  123. diffusers/pipelines/flux/pipeline_flux_fill.py +1 -1
  124. diffusers/pipelines/flux/pipeline_flux_img2img.py +1 -1
  125. diffusers/pipelines/flux/pipeline_flux_inpaint.py +1 -1
  126. diffusers/pipelines/flux/pipeline_flux_kontext.py +1134 -0
  127. diffusers/pipelines/flux/pipeline_flux_kontext_inpaint.py +1460 -0
  128. diffusers/pipelines/flux/pipeline_flux_prior_redux.py +1 -1
  129. diffusers/pipelines/flux/pipeline_output.py +6 -4
  130. diffusers/pipelines/hidream_image/pipeline_hidream_image.py +5 -5
  131. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +25 -24
  132. diffusers/pipelines/ltx/pipeline_ltx.py +13 -12
  133. diffusers/pipelines/ltx/pipeline_ltx_condition.py +10 -9
  134. diffusers/pipelines/ltx/pipeline_ltx_image2video.py +13 -12
  135. diffusers/pipelines/mochi/pipeline_mochi.py +9 -8
  136. diffusers/pipelines/pipeline_flax_utils.py +2 -2
  137. diffusers/pipelines/pipeline_loading_utils.py +24 -2
  138. diffusers/pipelines/pipeline_utils.py +22 -15
  139. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +3 -1
  140. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +20 -0
  141. diffusers/pipelines/qwenimage/__init__.py +55 -0
  142. diffusers/pipelines/qwenimage/pipeline_output.py +21 -0
  143. diffusers/pipelines/qwenimage/pipeline_qwenimage.py +726 -0
  144. diffusers/pipelines/qwenimage/pipeline_qwenimage_edit.py +882 -0
  145. diffusers/pipelines/qwenimage/pipeline_qwenimage_img2img.py +829 -0
  146. diffusers/pipelines/qwenimage/pipeline_qwenimage_inpaint.py +1015 -0
  147. diffusers/pipelines/sana/pipeline_sana_sprint.py +5 -5
  148. diffusers/pipelines/skyreels_v2/__init__.py +59 -0
  149. diffusers/pipelines/skyreels_v2/pipeline_output.py +20 -0
  150. diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2.py +610 -0
  151. diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing.py +978 -0
  152. diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_i2v.py +1059 -0
  153. diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_v2v.py +1063 -0
  154. diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_i2v.py +745 -0
  155. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +2 -1
  156. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -1
  157. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +1 -1
  158. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +2 -1
  159. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +6 -5
  160. diffusers/pipelines/wan/pipeline_wan.py +78 -20
  161. diffusers/pipelines/wan/pipeline_wan_i2v.py +112 -32
  162. diffusers/pipelines/wan/pipeline_wan_vace.py +1 -2
  163. diffusers/quantizers/__init__.py +1 -177
  164. diffusers/quantizers/base.py +11 -0
  165. diffusers/quantizers/gguf/utils.py +92 -3
  166. diffusers/quantizers/pipe_quant_config.py +202 -0
  167. diffusers/quantizers/torchao/torchao_quantizer.py +26 -0
  168. diffusers/schedulers/scheduling_deis_multistep.py +8 -1
  169. diffusers/schedulers/scheduling_dpmsolver_multistep.py +6 -0
  170. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +6 -0
  171. diffusers/schedulers/scheduling_scm.py +0 -1
  172. diffusers/schedulers/scheduling_unipc_multistep.py +10 -1
  173. diffusers/schedulers/scheduling_utils.py +2 -2
  174. diffusers/schedulers/scheduling_utils_flax.py +1 -1
  175. diffusers/training_utils.py +78 -0
  176. diffusers/utils/__init__.py +10 -0
  177. diffusers/utils/constants.py +4 -0
  178. diffusers/utils/dummy_pt_objects.py +312 -0
  179. diffusers/utils/dummy_torch_and_transformers_objects.py +255 -0
  180. diffusers/utils/dynamic_modules_utils.py +84 -25
  181. diffusers/utils/hub_utils.py +33 -17
  182. diffusers/utils/import_utils.py +70 -0
  183. diffusers/utils/peft_utils.py +11 -8
  184. diffusers/utils/testing_utils.py +136 -10
  185. diffusers/utils/torch_utils.py +18 -0
  186. {diffusers-0.34.0.dist-info → diffusers-0.35.0.dist-info}/METADATA +6 -6
  187. {diffusers-0.34.0.dist-info → diffusers-0.35.0.dist-info}/RECORD +191 -127
  188. {diffusers-0.34.0.dist-info → diffusers-0.35.0.dist-info}/LICENSE +0 -0
  189. {diffusers-0.34.0.dist-info → diffusers-0.35.0.dist-info}/WHEEL +0 -0
  190. {diffusers-0.34.0.dist-info → diffusers-0.35.0.dist-info}/entry_points.txt +0 -0
  191. {diffusers-0.34.0.dist-info → diffusers-0.35.0.dist-info}/top_level.txt +0 -0
@@ -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
@@ -0,0 +1,56 @@
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
+ from typing import Optional
16
+
17
+ import torch
18
+
19
+ from ..models.attention import AttentionModuleMixin, FeedForward, LuminaFeedForward
20
+ from ..models.attention_processor import Attention, MochiAttention
21
+
22
+
23
+ _ATTENTION_CLASSES = (Attention, MochiAttention, AttentionModuleMixin)
24
+ _FEEDFORWARD_CLASSES = (FeedForward, LuminaFeedForward)
25
+
26
+ _SPATIAL_TRANSFORMER_BLOCK_IDENTIFIERS = ("blocks", "transformer_blocks", "single_transformer_blocks", "layers")
27
+ _TEMPORAL_TRANSFORMER_BLOCK_IDENTIFIERS = ("temporal_transformer_blocks",)
28
+ _CROSS_TRANSFORMER_BLOCK_IDENTIFIERS = ("blocks", "transformer_blocks", "layers")
29
+
30
+ _ALL_TRANSFORMER_BLOCK_IDENTIFIERS = tuple(
31
+ {
32
+ *_SPATIAL_TRANSFORMER_BLOCK_IDENTIFIERS,
33
+ *_TEMPORAL_TRANSFORMER_BLOCK_IDENTIFIERS,
34
+ *_CROSS_TRANSFORMER_BLOCK_IDENTIFIERS,
35
+ }
36
+ )
37
+
38
+ # Layers supported for group offloading and layerwise casting
39
+ _GO_LC_SUPPORTED_PYTORCH_LAYERS = (
40
+ torch.nn.Conv1d,
41
+ torch.nn.Conv2d,
42
+ torch.nn.Conv3d,
43
+ torch.nn.ConvTranspose1d,
44
+ torch.nn.ConvTranspose2d,
45
+ torch.nn.ConvTranspose3d,
46
+ torch.nn.Linear,
47
+ # TODO(aryan): look into torch.nn.LayerNorm, torch.nn.GroupNorm later, seems to be causing some issues with CogVideoX
48
+ # because of double invocation of the same norm layer in CogVideoXLayerNorm
49
+ )
50
+
51
+
52
+ def _get_submodule_from_fqn(module: torch.nn.Module, fqn: str) -> Optional[torch.nn.Module]:
53
+ for submodule_name, submodule in module.named_modules():
54
+ if submodule_name == fqn:
55
+ return submodule
56
+ return None