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,672 @@
1
+ # Copyright 2023 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 inspect
16
+ import re
17
+ from collections import OrderedDict
18
+ from dataclasses import dataclass, field, fields
19
+ from typing import Any, Dict, List, Literal, Optional, Type, Union
20
+
21
+ import torch
22
+
23
+ from ..configuration_utils import ConfigMixin, FrozenDict
24
+ from ..utils import is_torch_available, logging
25
+
26
+
27
+ if is_torch_available():
28
+ pass
29
+
30
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
31
+
32
+
33
+ class InsertableDict(OrderedDict):
34
+ def insert(self, key, value, index):
35
+ items = list(self.items())
36
+
37
+ # Remove key if it already exists to avoid duplicates
38
+ items = [(k, v) for k, v in items if k != key]
39
+
40
+ # Insert at the specified index
41
+ items.insert(index, (key, value))
42
+
43
+ # Clear and update self
44
+ self.clear()
45
+ self.update(items)
46
+
47
+ # Return self for method chaining
48
+ return self
49
+
50
+ def __repr__(self):
51
+ if not self:
52
+ return "InsertableDict()"
53
+
54
+ items = []
55
+ for i, (key, value) in enumerate(self.items()):
56
+ if isinstance(value, type):
57
+ # For classes, show class name and <class ...>
58
+ obj_repr = f"<class '{value.__module__}.{value.__name__}'>"
59
+ else:
60
+ # For objects (instances) and other types, show class name and module
61
+ obj_repr = f"<obj '{value.__class__.__module__}.{value.__class__.__name__}'>"
62
+ items.append(f"{i}: ({repr(key)}, {obj_repr})")
63
+
64
+ return "InsertableDict([\n " + ",\n ".join(items) + "\n])"
65
+
66
+
67
+ # YiYi TODO:
68
+ # 1. validate the dataclass fields
69
+ # 2. improve the docstring and potentially add a validator for load methods, make sure they are valid inputs to pass to from_pretrained()
70
+ @dataclass
71
+ class ComponentSpec:
72
+ """Specification for a pipeline component.
73
+
74
+ A component can be created in two ways:
75
+ 1. From scratch using __init__ with a config dict
76
+ 2. using `from_pretrained`
77
+
78
+ Attributes:
79
+ name: Name of the component
80
+ type_hint: Type of the component (e.g. UNet2DConditionModel)
81
+ description: Optional description of the component
82
+ config: Optional config dict for __init__ creation
83
+ repo: Optional repo path for from_pretrained creation
84
+ subfolder: Optional subfolder in repo
85
+ variant: Optional variant in repo
86
+ revision: Optional revision in repo
87
+ default_creation_method: Preferred creation method - "from_config" or "from_pretrained"
88
+ """
89
+
90
+ name: Optional[str] = None
91
+ type_hint: Optional[Type] = None
92
+ description: Optional[str] = None
93
+ config: Optional[FrozenDict] = None
94
+ # YiYi Notes: should we change it to pretrained_model_name_or_path for consistency? a bit long for a field name
95
+ repo: Optional[Union[str, List[str]]] = field(default=None, metadata={"loading": True})
96
+ subfolder: Optional[str] = field(default="", metadata={"loading": True})
97
+ variant: Optional[str] = field(default=None, metadata={"loading": True})
98
+ revision: Optional[str] = field(default=None, metadata={"loading": True})
99
+ default_creation_method: Literal["from_config", "from_pretrained"] = "from_pretrained"
100
+
101
+ def __hash__(self):
102
+ """Make ComponentSpec hashable, using load_id as the hash value."""
103
+ return hash((self.name, self.load_id, self.default_creation_method))
104
+
105
+ def __eq__(self, other):
106
+ """Compare ComponentSpec objects based on name and load_id."""
107
+ if not isinstance(other, ComponentSpec):
108
+ return False
109
+ return (
110
+ self.name == other.name
111
+ and self.load_id == other.load_id
112
+ and self.default_creation_method == other.default_creation_method
113
+ )
114
+
115
+ @classmethod
116
+ def from_component(cls, name: str, component: Any) -> Any:
117
+ """Create a ComponentSpec from a Component.
118
+
119
+ Currently supports:
120
+ - Components created with `ComponentSpec.load()` method
121
+ - Components that are ConfigMixin subclasses but not nn.Modules (e.g. schedulers, guiders)
122
+
123
+ Args:
124
+ name: Name of the component
125
+ component: Component object to create spec from
126
+
127
+ Returns:
128
+ ComponentSpec object
129
+
130
+ Raises:
131
+ ValueError: If component is not supported (e.g. nn.Module without load_id, non-ConfigMixin)
132
+ """
133
+
134
+ # Check if component was created with ComponentSpec.load()
135
+ if hasattr(component, "_diffusers_load_id") and component._diffusers_load_id != "null":
136
+ # component has a usable load_id -> from_pretrained, no warning needed
137
+ default_creation_method = "from_pretrained"
138
+ else:
139
+ # Component doesn't have a usable load_id, check if it's a nn.Module
140
+ if isinstance(component, torch.nn.Module):
141
+ raise ValueError(
142
+ "Cannot create ComponentSpec from a nn.Module that was not created with `ComponentSpec.load()` method."
143
+ )
144
+ # ConfigMixin objects without weights (e.g. scheduler & guider) can be recreated with from_config
145
+ elif isinstance(component, ConfigMixin):
146
+ # warn if component was not created with `ComponentSpec`
147
+ if not hasattr(component, "_diffusers_load_id"):
148
+ logger.warning(
149
+ "Component was not created using `ComponentSpec`, defaulting to `from_config` creation method"
150
+ )
151
+ default_creation_method = "from_config"
152
+ else:
153
+ # Not a ConfigMixin and not created with `ComponentSpec.load()` method -> throw error
154
+ raise ValueError(
155
+ f"Cannot create ComponentSpec from {name}({component.__class__.__name__}). Currently ComponentSpec.from_component() only supports: "
156
+ f" - components created with `ComponentSpec.load()` method"
157
+ f" - components that are a subclass of ConfigMixin but not a nn.Module (e.g. guider, scheduler)."
158
+ )
159
+
160
+ type_hint = component.__class__
161
+
162
+ if isinstance(component, ConfigMixin) and default_creation_method == "from_config":
163
+ config = component.config
164
+ else:
165
+ config = None
166
+ if hasattr(component, "_diffusers_load_id") and component._diffusers_load_id != "null":
167
+ load_spec = cls.decode_load_id(component._diffusers_load_id)
168
+ else:
169
+ load_spec = {}
170
+
171
+ return cls(
172
+ name=name, type_hint=type_hint, config=config, default_creation_method=default_creation_method, **load_spec
173
+ )
174
+
175
+ @classmethod
176
+ def loading_fields(cls) -> List[str]:
177
+ """
178
+ Return the names of all loading‐related fields (i.e. those whose field.metadata["loading"] is True).
179
+ """
180
+ return [f.name for f in fields(cls) if f.metadata.get("loading", False)]
181
+
182
+ @property
183
+ def load_id(self) -> str:
184
+ """
185
+ Unique identifier for this spec's pretrained load, composed of repo|subfolder|variant|revision (no empty
186
+ segments).
187
+ """
188
+ if self.default_creation_method == "from_config":
189
+ return "null"
190
+ parts = [getattr(self, k) for k in self.loading_fields()]
191
+ parts = ["null" if p is None else p for p in parts]
192
+ return "|".join(p for p in parts if p)
193
+
194
+ @classmethod
195
+ def decode_load_id(cls, load_id: str) -> Dict[str, Optional[str]]:
196
+ """
197
+ Decode a load_id string back into a dictionary of loading fields and values.
198
+
199
+ Args:
200
+ load_id: The load_id string to decode, format: "repo|subfolder|variant|revision"
201
+ where None values are represented as "null"
202
+
203
+ Returns:
204
+ Dict mapping loading field names to their values. e.g. {
205
+ "repo": "path/to/repo", "subfolder": "subfolder", "variant": "variant", "revision": "revision"
206
+ } If a segment value is "null", it's replaced with None. Returns None if load_id is "null" (indicating
207
+ component not created with `load` method).
208
+ """
209
+
210
+ # Get all loading fields in order
211
+ loading_fields = cls.loading_fields()
212
+ result = {f: None for f in loading_fields}
213
+
214
+ if load_id == "null":
215
+ return result
216
+
217
+ # Split the load_id
218
+ parts = load_id.split("|")
219
+
220
+ # Map parts to loading fields by position
221
+ for i, part in enumerate(parts):
222
+ if i < len(loading_fields):
223
+ # Convert "null" string back to None
224
+ result[loading_fields[i]] = None if part == "null" else part
225
+
226
+ return result
227
+
228
+ # YiYi TODO: I think we should only support ConfigMixin for this method (after we make guider and image_processors config mixin)
229
+ # otherwise we cannot do spec -> spec.create() -> component -> ComponentSpec.from_component(component)
230
+ # the config info is lost in the process
231
+ # remove error check in from_component spec and ModularPipeline.update_components() if we remove support for non configmixin in `create()` method
232
+ def create(self, config: Optional[Union[FrozenDict, Dict[str, Any]]] = None, **kwargs) -> Any:
233
+ """Create component using from_config with config."""
234
+
235
+ if self.type_hint is None or not isinstance(self.type_hint, type):
236
+ raise ValueError("`type_hint` is required when using from_config creation method.")
237
+
238
+ config = config or self.config or {}
239
+
240
+ if issubclass(self.type_hint, ConfigMixin):
241
+ component = self.type_hint.from_config(config, **kwargs)
242
+ else:
243
+ signature_params = inspect.signature(self.type_hint.__init__).parameters
244
+ init_kwargs = {}
245
+ for k, v in config.items():
246
+ if k in signature_params:
247
+ init_kwargs[k] = v
248
+ for k, v in kwargs.items():
249
+ if k in signature_params:
250
+ init_kwargs[k] = v
251
+ component = self.type_hint(**init_kwargs)
252
+
253
+ component._diffusers_load_id = "null"
254
+ if hasattr(component, "config"):
255
+ self.config = component.config
256
+
257
+ return component
258
+
259
+ # YiYi TODO: add guard for type of model, if it is supported by from_pretrained
260
+ def load(self, **kwargs) -> Any:
261
+ """Load component using from_pretrained."""
262
+
263
+ # select loading fields from kwargs passed from user: e.g. repo, subfolder, variant, revision, note the list could change
264
+ passed_loading_kwargs = {key: kwargs.pop(key) for key in self.loading_fields() if key in kwargs}
265
+ # merge loading field value in the spec with user passed values to create load_kwargs
266
+ load_kwargs = {key: passed_loading_kwargs.get(key, getattr(self, key)) for key in self.loading_fields()}
267
+ # repo is a required argument for from_pretrained, a.k.a. pretrained_model_name_or_path
268
+ repo = load_kwargs.pop("repo", None)
269
+ if repo is None:
270
+ raise ValueError(
271
+ "`repo` info is required when using `load` method (you can directly set it in `repo` field of the ComponentSpec or pass it as an argument)"
272
+ )
273
+
274
+ if self.type_hint is None:
275
+ try:
276
+ from diffusers import AutoModel
277
+
278
+ component = AutoModel.from_pretrained(repo, **load_kwargs, **kwargs)
279
+ except Exception as e:
280
+ raise ValueError(f"Unable to load {self.name} without `type_hint`: {e}")
281
+ # update type_hint if AutoModel load successfully
282
+ self.type_hint = component.__class__
283
+ else:
284
+ try:
285
+ component = self.type_hint.from_pretrained(repo, **load_kwargs, **kwargs)
286
+ except Exception as e:
287
+ raise ValueError(f"Unable to load {self.name} using load method: {e}")
288
+
289
+ self.repo = repo
290
+ for k, v in load_kwargs.items():
291
+ setattr(self, k, v)
292
+ component._diffusers_load_id = self.load_id
293
+
294
+ return component
295
+
296
+
297
+ @dataclass
298
+ class ConfigSpec:
299
+ """Specification for a pipeline configuration parameter."""
300
+
301
+ name: str
302
+ default: Any
303
+ description: Optional[str] = None
304
+
305
+
306
+ # YiYi Notes: both inputs and intermediate_inputs are InputParam objects
307
+ # however some fields are not relevant for intermediate_inputs
308
+ # e.g. unlike inputs, required only used in docstring for intermediate_inputs, we do not check if a required intermediate inputs is passed
309
+ # default is not used for intermediate_inputs, we only use default from inputs, so it is ignored if it is set for intermediate_inputs
310
+ # -> should we use different class for inputs and intermediate_inputs?
311
+ @dataclass
312
+ class InputParam:
313
+ """Specification for an input parameter."""
314
+
315
+ name: str = None
316
+ type_hint: Any = None
317
+ default: Any = None
318
+ required: bool = False
319
+ description: str = ""
320
+ kwargs_type: str = None # YiYi Notes: remove this feature (maybe)
321
+
322
+ def __repr__(self):
323
+ return f"<{self.name}: {'required' if self.required else 'optional'}, default={self.default}>"
324
+
325
+
326
+ @dataclass
327
+ class OutputParam:
328
+ """Specification for an output parameter."""
329
+
330
+ name: str
331
+ type_hint: Any = None
332
+ description: str = ""
333
+ kwargs_type: str = None # YiYi notes: remove this feature (maybe)
334
+
335
+ def __repr__(self):
336
+ return (
337
+ f"<{self.name}: {self.type_hint.__name__ if hasattr(self.type_hint, '__name__') else str(self.type_hint)}>"
338
+ )
339
+
340
+
341
+ def format_inputs_short(inputs):
342
+ """
343
+ Format input parameters into a string representation, with required params first followed by optional ones.
344
+
345
+ Args:
346
+ inputs: List of input parameters with 'required' and 'name' attributes, and 'default' for optional params
347
+
348
+ Returns:
349
+ str: Formatted string of input parameters
350
+
351
+ Example:
352
+ >>> inputs = [ ... InputParam(name="prompt", required=True), ... InputParam(name="image", required=True), ...
353
+ InputParam(name="guidance_scale", required=False, default=7.5), ... InputParam(name="num_inference_steps",
354
+ required=False, default=50) ... ] >>> format_inputs_short(inputs) 'prompt, image, guidance_scale=7.5,
355
+ num_inference_steps=50'
356
+ """
357
+ required_inputs = [param for param in inputs if param.required]
358
+ optional_inputs = [param for param in inputs if not param.required]
359
+
360
+ required_str = ", ".join(param.name for param in required_inputs)
361
+ optional_str = ", ".join(f"{param.name}={param.default}" for param in optional_inputs)
362
+
363
+ inputs_str = required_str
364
+ if optional_str:
365
+ inputs_str = f"{inputs_str}, {optional_str}" if required_str else optional_str
366
+
367
+ return inputs_str
368
+
369
+
370
+ def format_intermediates_short(intermediate_inputs, required_intermediate_inputs, intermediate_outputs):
371
+ """
372
+ Formats intermediate inputs and outputs of a block into a string representation.
373
+
374
+ Args:
375
+ intermediate_inputs: List of intermediate input parameters
376
+ required_intermediate_inputs: List of required intermediate input names
377
+ intermediate_outputs: List of intermediate output parameters
378
+
379
+ Returns:
380
+ str: Formatted string like:
381
+ Intermediates:
382
+ - inputs: Required(latents), dtype
383
+ - modified: latents # variables that appear in both inputs and outputs
384
+ - outputs: images # new outputs only
385
+ """
386
+ # Handle inputs
387
+ input_parts = []
388
+ for inp in intermediate_inputs:
389
+ if inp.name in required_intermediate_inputs:
390
+ input_parts.append(f"Required({inp.name})")
391
+ else:
392
+ if inp.name is None and inp.kwargs_type is not None:
393
+ inp_name = "*_" + inp.kwargs_type
394
+ else:
395
+ inp_name = inp.name
396
+ input_parts.append(inp_name)
397
+
398
+ # Handle modified variables (appear in both inputs and outputs)
399
+ inputs_set = {inp.name for inp in intermediate_inputs}
400
+ modified_parts = []
401
+ new_output_parts = []
402
+
403
+ for out in intermediate_outputs:
404
+ if out.name in inputs_set:
405
+ modified_parts.append(out.name)
406
+ else:
407
+ new_output_parts.append(out.name)
408
+
409
+ result = []
410
+ if input_parts:
411
+ result.append(f" - inputs: {', '.join(input_parts)}")
412
+ if modified_parts:
413
+ result.append(f" - modified: {', '.join(modified_parts)}")
414
+ if new_output_parts:
415
+ result.append(f" - outputs: {', '.join(new_output_parts)}")
416
+
417
+ return "\n".join(result) if result else " (none)"
418
+
419
+
420
+ def format_params(params, header="Args", indent_level=4, max_line_length=115):
421
+ """Format a list of InputParam or OutputParam objects into a readable string representation.
422
+
423
+ Args:
424
+ params: List of InputParam or OutputParam objects to format
425
+ header: Header text to use (e.g. "Args" or "Returns")
426
+ indent_level: Number of spaces to indent each parameter line (default: 4)
427
+ max_line_length: Maximum length for each line before wrapping (default: 115)
428
+
429
+ Returns:
430
+ A formatted string representing all parameters
431
+ """
432
+ if not params:
433
+ return ""
434
+
435
+ base_indent = " " * indent_level
436
+ param_indent = " " * (indent_level + 4)
437
+ desc_indent = " " * (indent_level + 8)
438
+ formatted_params = []
439
+
440
+ def get_type_str(type_hint):
441
+ if hasattr(type_hint, "__origin__") and type_hint.__origin__ is Union:
442
+ types = [t.__name__ if hasattr(t, "__name__") else str(t) for t in type_hint.__args__]
443
+ return f"Union[{', '.join(types)}]"
444
+ return type_hint.__name__ if hasattr(type_hint, "__name__") else str(type_hint)
445
+
446
+ def wrap_text(text, indent, max_length):
447
+ """Wrap text while preserving markdown links and maintaining indentation."""
448
+ words = text.split()
449
+ lines = []
450
+ current_line = []
451
+ current_length = 0
452
+
453
+ for word in words:
454
+ word_length = len(word) + (1 if current_line else 0)
455
+
456
+ if current_line and current_length + word_length > max_length:
457
+ lines.append(" ".join(current_line))
458
+ current_line = [word]
459
+ current_length = len(word)
460
+ else:
461
+ current_line.append(word)
462
+ current_length += word_length
463
+
464
+ if current_line:
465
+ lines.append(" ".join(current_line))
466
+
467
+ return f"\n{indent}".join(lines)
468
+
469
+ # Add the header
470
+ formatted_params.append(f"{base_indent}{header}:")
471
+
472
+ for param in params:
473
+ # Format parameter name and type
474
+ type_str = get_type_str(param.type_hint) if param.type_hint != Any else ""
475
+ # YiYi Notes: remove this line if we remove kwargs_type
476
+ name = f"**{param.kwargs_type}" if param.name is None and param.kwargs_type is not None else param.name
477
+ param_str = f"{param_indent}{name} (`{type_str}`"
478
+
479
+ # Add optional tag and default value if parameter is an InputParam and optional
480
+ if hasattr(param, "required"):
481
+ if not param.required:
482
+ param_str += ", *optional*"
483
+ if param.default is not None:
484
+ param_str += f", defaults to {param.default}"
485
+ param_str += "):"
486
+
487
+ # Add description on a new line with additional indentation and wrapping
488
+ if param.description:
489
+ desc = re.sub(r"\[(.*?)\]\((https?://[^\s\)]+)\)", r"[\1](\2)", param.description)
490
+ wrapped_desc = wrap_text(desc, desc_indent, max_line_length)
491
+ param_str += f"\n{desc_indent}{wrapped_desc}"
492
+
493
+ formatted_params.append(param_str)
494
+
495
+ return "\n\n".join(formatted_params)
496
+
497
+
498
+ def format_input_params(input_params, indent_level=4, max_line_length=115):
499
+ """Format a list of InputParam objects into a readable string representation.
500
+
501
+ Args:
502
+ input_params: List of InputParam objects to format
503
+ indent_level: Number of spaces to indent each parameter line (default: 4)
504
+ max_line_length: Maximum length for each line before wrapping (default: 115)
505
+
506
+ Returns:
507
+ A formatted string representing all input parameters
508
+ """
509
+ return format_params(input_params, "Inputs", indent_level, max_line_length)
510
+
511
+
512
+ def format_output_params(output_params, indent_level=4, max_line_length=115):
513
+ """Format a list of OutputParam objects into a readable string representation.
514
+
515
+ Args:
516
+ output_params: List of OutputParam objects to format
517
+ indent_level: Number of spaces to indent each parameter line (default: 4)
518
+ max_line_length: Maximum length for each line before wrapping (default: 115)
519
+
520
+ Returns:
521
+ A formatted string representing all output parameters
522
+ """
523
+ return format_params(output_params, "Outputs", indent_level, max_line_length)
524
+
525
+
526
+ def format_components(components, indent_level=4, max_line_length=115, add_empty_lines=True):
527
+ """Format a list of ComponentSpec objects into a readable string representation.
528
+
529
+ Args:
530
+ components: List of ComponentSpec objects to format
531
+ indent_level: Number of spaces to indent each component line (default: 4)
532
+ max_line_length: Maximum length for each line before wrapping (default: 115)
533
+ add_empty_lines: Whether to add empty lines between components (default: True)
534
+
535
+ Returns:
536
+ A formatted string representing all components
537
+ """
538
+ if not components:
539
+ return ""
540
+
541
+ base_indent = " " * indent_level
542
+ component_indent = " " * (indent_level + 4)
543
+ formatted_components = []
544
+
545
+ # Add the header
546
+ formatted_components.append(f"{base_indent}Components:")
547
+ if add_empty_lines:
548
+ formatted_components.append("")
549
+
550
+ # Add each component with optional empty lines between them
551
+ for i, component in enumerate(components):
552
+ # Get type name, handling special cases
553
+ type_name = (
554
+ component.type_hint.__name__ if hasattr(component.type_hint, "__name__") else str(component.type_hint)
555
+ )
556
+
557
+ component_desc = f"{component_indent}{component.name} (`{type_name}`)"
558
+ if component.description:
559
+ component_desc += f": {component.description}"
560
+
561
+ # Get the loading fields dynamically
562
+ loading_field_values = []
563
+ for field_name in component.loading_fields():
564
+ field_value = getattr(component, field_name)
565
+ if field_value is not None:
566
+ loading_field_values.append(f"{field_name}={field_value}")
567
+
568
+ # Add loading field information if available
569
+ if loading_field_values:
570
+ component_desc += f" [{', '.join(loading_field_values)}]"
571
+
572
+ formatted_components.append(component_desc)
573
+
574
+ # Add an empty line after each component except the last one
575
+ if add_empty_lines and i < len(components) - 1:
576
+ formatted_components.append("")
577
+
578
+ return "\n".join(formatted_components)
579
+
580
+
581
+ def format_configs(configs, indent_level=4, max_line_length=115, add_empty_lines=True):
582
+ """Format a list of ConfigSpec objects into a readable string representation.
583
+
584
+ Args:
585
+ configs: List of ConfigSpec objects to format
586
+ indent_level: Number of spaces to indent each config line (default: 4)
587
+ max_line_length: Maximum length for each line before wrapping (default: 115)
588
+ add_empty_lines: Whether to add empty lines between configs (default: True)
589
+
590
+ Returns:
591
+ A formatted string representing all configs
592
+ """
593
+ if not configs:
594
+ return ""
595
+
596
+ base_indent = " " * indent_level
597
+ config_indent = " " * (indent_level + 4)
598
+ formatted_configs = []
599
+
600
+ # Add the header
601
+ formatted_configs.append(f"{base_indent}Configs:")
602
+ if add_empty_lines:
603
+ formatted_configs.append("")
604
+
605
+ # Add each config with optional empty lines between them
606
+ for i, config in enumerate(configs):
607
+ config_desc = f"{config_indent}{config.name} (default: {config.default})"
608
+ if config.description:
609
+ config_desc += f": {config.description}"
610
+ formatted_configs.append(config_desc)
611
+
612
+ # Add an empty line after each config except the last one
613
+ if add_empty_lines and i < len(configs) - 1:
614
+ formatted_configs.append("")
615
+
616
+ return "\n".join(formatted_configs)
617
+
618
+
619
+ def make_doc_string(
620
+ inputs,
621
+ outputs,
622
+ description="",
623
+ class_name=None,
624
+ expected_components=None,
625
+ expected_configs=None,
626
+ ):
627
+ """
628
+ Generates a formatted documentation string describing the pipeline block's parameters and structure.
629
+
630
+ Args:
631
+ inputs: List of input parameters
632
+ intermediate_inputs: List of intermediate input parameters
633
+ outputs: List of output parameters
634
+ description (str, *optional*): Description of the block
635
+ class_name (str, *optional*): Name of the class to include in the documentation
636
+ expected_components (List[ComponentSpec], *optional*): List of expected components
637
+ expected_configs (List[ConfigSpec], *optional*): List of expected configurations
638
+
639
+ Returns:
640
+ str: A formatted string containing information about components, configs, call parameters,
641
+ intermediate inputs/outputs, and final outputs.
642
+ """
643
+ output = ""
644
+
645
+ # Add class name if provided
646
+ if class_name:
647
+ output += f"class {class_name}\n\n"
648
+
649
+ # Add description
650
+ if description:
651
+ desc_lines = description.strip().split("\n")
652
+ aligned_desc = "\n".join(" " + line for line in desc_lines)
653
+ output += aligned_desc + "\n\n"
654
+
655
+ # Add components section if provided
656
+ if expected_components and len(expected_components) > 0:
657
+ components_str = format_components(expected_components, indent_level=2)
658
+ output += components_str + "\n\n"
659
+
660
+ # Add configs section if provided
661
+ if expected_configs and len(expected_configs) > 0:
662
+ configs_str = format_configs(expected_configs, indent_level=2)
663
+ output += configs_str + "\n\n"
664
+
665
+ # Add inputs section
666
+ output += format_input_params(inputs, indent_level=2)
667
+
668
+ # Add outputs section
669
+ output += "\n\n"
670
+ output += format_output_params(outputs, indent_level=2)
671
+
672
+ return output