Skip to content

Commit 74b908b

Browse files
committed
style
1 parent 7d2a633 commit 74b908b

28 files changed

Lines changed: 1915 additions & 1125 deletions

src/diffusers/__init__.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,8 @@
3838
"hooks": [],
3939
"loaders": ["FromOriginalModelMixin"],
4040
"models": [],
41-
"pipelines": [],
4241
"modular_pipelines": [],
42+
"pipelines": [],
4343
"quantizers.quantization_config": [],
4444
"schedulers": [],
4545
"utils": [
@@ -147,8 +147,8 @@
147147
[
148148
"FasterCacheConfig",
149149
"HookRegistry",
150-
"PyramidAttentionBroadcastConfig",
151150
"LayerSkipConfig",
151+
"PyramidAttentionBroadcastConfig",
152152
"SmoothedEnergyGuidanceConfig",
153153
"apply_faster_cache",
154154
"apply_layer_skip",
@@ -235,6 +235,15 @@
235235
"WanVACETransformer3DModel",
236236
]
237237
)
238+
_import_structure["modular_pipelines"].extend(
239+
[
240+
"ComponentsManager",
241+
"ComponentSpec",
242+
"ModularLoader",
243+
"ModularPipeline",
244+
"ModularPipelineBlocks",
245+
]
246+
)
238247
_import_structure["optimization"] = [
239248
"get_constant_schedule",
240249
"get_constant_schedule_with_warmup",
@@ -266,15 +275,6 @@
266275
"StableDiffusionMixin",
267276
]
268277
)
269-
_import_structure["modular_pipelines"].extend(
270-
[
271-
"ModularLoader",
272-
"ModularPipeline",
273-
"ModularPipelineBlocks",
274-
"ComponentSpec",
275-
"ComponentsManager",
276-
]
277-
)
278278
_import_structure["quantizers"] = ["DiffusersQuantizer"]
279279
_import_structure["schedulers"].extend(
280280
[
@@ -356,6 +356,12 @@
356356
]
357357

358358
else:
359+
_import_structure["modular_pipelines"].extend(
360+
[
361+
"StableDiffusionXLAutoPipeline",
362+
"StableDiffusionXLModularLoader",
363+
]
364+
)
359365
_import_structure["pipelines"].extend(
360366
[
361367
"AllegroPipeline",
@@ -565,12 +571,6 @@
565571
"WuerstchenPriorPipeline",
566572
]
567573
)
568-
_import_structure["modular_pipelines"].extend(
569-
[
570-
"StableDiffusionXLAutoPipeline",
571-
"StableDiffusionXLModularLoader",
572-
]
573-
)
574574

575575

576576
try:

src/diffusers/commands/custom_blocks.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
EXPECTED_PARENT_CLASSES = ["PipelineBlock"]
3131
CONFIG = "config.json"
3232

33+
3334
def conversion_command_factory(args: Namespace):
3435
return CustomBlocksCommand(args.block_module_name, args.block_class_name)
3536

@@ -45,7 +46,10 @@ def register_subcommand(parser: ArgumentParser):
4546
help="Module filename in which the custom block will be implemented.",
4647
)
4748
conversion_parser.add_argument(
48-
"--block_class_name", type=str, default=None, help="Name of the custom block. If provided None, we will try to infer it."
49+
"--block_class_name",
50+
type=str,
51+
default=None,
52+
help="Name of the custom block. If provided None, we will try to infer it.",
4953
)
5054
conversion_parser.set_defaults(func=conversion_command_factory)
5155

@@ -71,7 +75,7 @@ def run(self):
7175
f"Found classes: {classes_found} will be using {classes_found[0]}. "
7276
"If this needs to be changed, re-run the command specifying `block_class_name`."
7377
)
74-
child_class, parent_class = out[0][0], out[0][1]
78+
child_class, parent_class = out[0][0], out[0][1]
7579

7680
# dynamically get the custom block and initialize it to call `save_pretrained` in the current directory.
7781
# the user is responsible for running it, so I guess that is safe?
@@ -107,10 +111,7 @@ def _get_class_names(self, file_path):
107111
continue
108112

109113
# extract all base names for this class
110-
base_names = [
111-
bname for b in node.bases
112-
if (bname := self._get_base_name(b)) is not None
113-
]
114+
base_names = [bname for b in node.bases if (bname := self._get_base_name(b)) is not None]
114115

115116
# for each allowed base that appears in the class's bases, emit a tuple
116117
for allowed in EXPECTED_PARENT_CLASSES:
@@ -131,4 +132,3 @@ def _create_automap(self, parent_class, child_class):
131132
module = str(self.block_module_name).replace(".py", "").rsplit(".", 1)[-1]
132133
auto_map = {f"{parent_class}": f"{module}.{child_class}"}
133134
return {"auto_map": auto_map}
134-

src/diffusers/guiders/__init__.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,12 @@
2626
from .smoothed_energy_guidance import SmoothedEnergyGuidance
2727
from .tangential_classifier_free_guidance import TangentialClassifierFreeGuidance
2828

29-
GuiderType = Union[AdaptiveProjectedGuidance, AutoGuidance, ClassifierFreeGuidance, ClassifierFreeZeroStarGuidance, SkipLayerGuidance, SmoothedEnergyGuidance, TangentialClassifierFreeGuidance]
29+
GuiderType = Union[
30+
AdaptiveProjectedGuidance,
31+
AutoGuidance,
32+
ClassifierFreeGuidance,
33+
ClassifierFreeZeroStarGuidance,
34+
SkipLayerGuidance,
35+
SmoothedEnergyGuidance,
36+
TangentialClassifierFreeGuidance,
37+
]

src/diffusers/guiders/adaptive_projected_guidance.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
class AdaptiveProjectedGuidance(BaseGuidance):
2828
"""
2929
Adaptive Projected Guidance (APG): https://huggingface.co/papers/2410.02416
30-
30+
3131
Args:
3232
guidance_scale (`float`, defaults to `7.5`):
3333
The scale parameter for classifier-free guidance. Higher values result in stronger conditioning on the text
@@ -74,8 +74,9 @@ def __init__(
7474
self.use_original_formulation = use_original_formulation
7575
self.momentum_buffer = None
7676

77-
def prepare_inputs(self, data: "BlockState", input_fields: Optional[Dict[str, Union[str, Tuple[str, str]]]] = None) -> List["BlockState"]:
78-
77+
def prepare_inputs(
78+
self, data: "BlockState", input_fields: Optional[Dict[str, Union[str, Tuple[str, str]]]] = None
79+
) -> List["BlockState"]:
7980
if input_fields is None:
8081
input_fields = self._input_fields
8182

src/diffusers/guiders/auto_guidance.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
class AutoGuidance(BaseGuidance):
3030
"""
3131
AutoGuidance: https://huggingface.co/papers/2406.02507
32-
32+
3333
Args:
3434
guidance_scale (`float`, defaults to `7.5`):
3535
The scale parameter for classifier-free guidance. Higher values result in stronger conditioning on the text
@@ -86,7 +86,9 @@ def __init__(
8686
)
8787
if auto_guidance_layers is not None and auto_guidance_config is not None:
8888
raise ValueError("Only one of `auto_guidance_layers` or `auto_guidance_config` can be provided.")
89-
if (dropout is None and auto_guidance_layers is not None) or (dropout is not None and auto_guidance_layers is None):
89+
if (dropout is None and auto_guidance_layers is not None) or (
90+
dropout is not None and auto_guidance_layers is None
91+
):
9092
raise ValueError("`dropout` must be provided if `auto_guidance_layers` is provided.")
9193

9294
if auto_guidance_layers is not None:
@@ -96,7 +98,9 @@ def __init__(
9698
raise ValueError(
9799
f"Expected `auto_guidance_layers` to be an int or a list of ints, but got {type(auto_guidance_layers)}."
98100
)
99-
auto_guidance_config = [LayerSkipConfig(layer, fqn="auto", dropout=dropout) for layer in auto_guidance_layers]
101+
auto_guidance_config = [
102+
LayerSkipConfig(layer, fqn="auto", dropout=dropout) for layer in auto_guidance_layers
103+
]
100104

101105
if isinstance(auto_guidance_config, LayerSkipConfig):
102106
auto_guidance_config = [auto_guidance_config]
@@ -121,8 +125,9 @@ def cleanup_models(self, denoiser: torch.nn.Module) -> None:
121125
registry = HookRegistry.check_if_exists_or_initialize(denoiser)
122126
registry.remove_hook(name, recurse=True)
123127

124-
def prepare_inputs(self, data: "BlockState", input_fields: Optional[Dict[str, Union[str, Tuple[str, str]]]] = None) -> List["BlockState"]:
125-
128+
def prepare_inputs(
129+
self, data: "BlockState", input_fields: Optional[Dict[str, Union[str, Tuple[str, str]]]] = None
130+
) -> List["BlockState"]:
126131
if input_fields is None:
127132
input_fields = self._input_fields
128133

src/diffusers/guiders/classifier_free_guidance.py

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -27,25 +27,25 @@
2727
class ClassifierFreeGuidance(BaseGuidance):
2828
"""
2929
Classifier-free guidance (CFG): https://huggingface.co/papers/2207.12598
30-
30+
3131
CFG is a technique used to improve generation quality and condition-following in diffusion models. It works by
3232
jointly training a model on both conditional and unconditional data, and using a weighted sum of the two during
33-
inference. This allows the model to tradeoff between generation quality and sample diversity.
34-
The original paper proposes scaling and shifting the conditional distribution based on the difference between
35-
conditional and unconditional predictions. [x_pred = x_cond + scale * (x_cond - x_uncond)]
36-
33+
inference. This allows the model to tradeoff between generation quality and sample diversity. The original paper
34+
proposes scaling and shifting the conditional distribution based on the difference between conditional and
35+
unconditional predictions. [x_pred = x_cond + scale * (x_cond - x_uncond)]
36+
3737
Diffusers implemented the scaling and shifting on the unconditional prediction instead based on the [Imagen
3838
paper](https://huggingface.co/papers/2205.11487), which is equivalent to what the original paper proposed in
3939
theory. [x_pred = x_uncond + scale * (x_cond - x_uncond)]
40-
40+
4141
The intution behind the original formulation can be thought of as moving the conditional distribution estimates
4242
further away from the unconditional distribution estimates, while the diffusers-native implementation can be
4343
thought of as moving the unconditional distribution towards the conditional distribution estimates to get rid of
4444
the unconditional predictions (usually negative features like "bad quality, bad anotomy, watermarks", etc.)
45-
45+
4646
The `use_original_formulation` argument can be set to `True` to use the original CFG formulation mentioned in the
4747
paper. By default, we use the diffusers-native implementation that has been in the codebase for a long time.
48-
48+
4949
Args:
5050
guidance_scale (`float`, defaults to `7.5`):
5151
The scale parameter for classifier-free guidance. Higher values result in stronger conditioning on the text
@@ -68,16 +68,22 @@ class ClassifierFreeGuidance(BaseGuidance):
6868
_input_predictions = ["pred_cond", "pred_uncond"]
6969

7070
def __init__(
71-
self, guidance_scale: float = 7.5, guidance_rescale: float = 0.0, use_original_formulation: bool = False, start: float = 0.0, stop: float = 1.0
71+
self,
72+
guidance_scale: float = 7.5,
73+
guidance_rescale: float = 0.0,
74+
use_original_formulation: bool = False,
75+
start: float = 0.0,
76+
stop: float = 1.0,
7277
):
7378
super().__init__(start, stop)
7479

7580
self.guidance_scale = guidance_scale
7681
self.guidance_rescale = guidance_rescale
7782
self.use_original_formulation = use_original_formulation
7883

79-
def prepare_inputs(self, data: "BlockState", input_fields: Optional[Dict[str, Union[str, Tuple[str, str]]]] = None) -> List["BlockState"]:
80-
84+
def prepare_inputs(
85+
self, data: "BlockState", input_fields: Optional[Dict[str, Union[str, Tuple[str, str]]]] = None
86+
) -> List["BlockState"]:
8187
if input_fields is None:
8288
input_fields = self._input_fields
8389

src/diffusers/guiders/classifier_free_zero_star_guidance.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,14 @@
2727
class ClassifierFreeZeroStarGuidance(BaseGuidance):
2828
"""
2929
Classifier-free Zero* (CFG-Zero*): https://huggingface.co/papers/2503.18886
30-
30+
3131
This is an implementation of the Classifier-Free Zero* guidance technique, which is a variant of classifier-free
3232
guidance. It proposes zero initialization of the noise predictions for the first few steps of the diffusion
3333
process, and also introduces an optimal rescaling factor for the noise predictions, which can help in improving the
3434
quality of generated images.
35-
35+
3636
The authors of the paper suggest setting zero initialization in the first 4% of the inference steps.
37-
37+
3838
Args:
3939
guidance_scale (`float`, defaults to `7.5`):
4040
The scale parameter for classifier-free guidance. Higher values result in stronger conditioning on the text
@@ -74,8 +74,9 @@ def __init__(
7474
self.guidance_rescale = guidance_rescale
7575
self.use_original_formulation = use_original_formulation
7676

77-
def prepare_inputs(self, data: "BlockState", input_fields: Optional[Dict[str, Union[str, Tuple[str, str]]]] = None) -> List["BlockState"]:
78-
77+
def prepare_inputs(
78+
self, data: "BlockState", input_fields: Optional[Dict[str, Union[str, Tuple[str, str]]]] = None
79+
) -> List["BlockState"]:
7980
if input_fields is None:
8081
input_fields = self._input_fields
8182

0 commit comments

Comments
 (0)