diffusers 0.29.0__py3-none-any.whl → 0.29.2__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.
@@ -0,0 +1,418 @@
1
+ # Copyright 2024 Stability AI, The HuggingFace Team and The InstantX 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
+
16
+ from dataclasses import dataclass
17
+ from typing import Any, Dict, List, Optional, Tuple, Union
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+
22
+ from ..configuration_utils import ConfigMixin, register_to_config
23
+ from ..loaders import FromOriginalModelMixin, PeftAdapterMixin
24
+ from ..models.attention import JointTransformerBlock
25
+ from ..models.attention_processor import Attention, AttentionProcessor
26
+ from ..models.modeling_outputs import Transformer2DModelOutput
27
+ from ..models.modeling_utils import ModelMixin
28
+ from ..utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
29
+ from .controlnet import BaseOutput, zero_module
30
+ from .embeddings import CombinedTimestepTextProjEmbeddings, PatchEmbed
31
+
32
+
33
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
34
+
35
+
36
+ @dataclass
37
+ class SD3ControlNetOutput(BaseOutput):
38
+ controlnet_block_samples: Tuple[torch.Tensor]
39
+
40
+
41
+ class SD3ControlNetModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
42
+ _supports_gradient_checkpointing = True
43
+
44
+ @register_to_config
45
+ def __init__(
46
+ self,
47
+ sample_size: int = 128,
48
+ patch_size: int = 2,
49
+ in_channels: int = 16,
50
+ num_layers: int = 18,
51
+ attention_head_dim: int = 64,
52
+ num_attention_heads: int = 18,
53
+ joint_attention_dim: int = 4096,
54
+ caption_projection_dim: int = 1152,
55
+ pooled_projection_dim: int = 2048,
56
+ out_channels: int = 16,
57
+ pos_embed_max_size: int = 96,
58
+ ):
59
+ super().__init__()
60
+ default_out_channels = in_channels
61
+ self.out_channels = out_channels if out_channels is not None else default_out_channels
62
+ self.inner_dim = num_attention_heads * attention_head_dim
63
+
64
+ self.pos_embed = PatchEmbed(
65
+ height=sample_size,
66
+ width=sample_size,
67
+ patch_size=patch_size,
68
+ in_channels=in_channels,
69
+ embed_dim=self.inner_dim,
70
+ pos_embed_max_size=pos_embed_max_size,
71
+ )
72
+ self.time_text_embed = CombinedTimestepTextProjEmbeddings(
73
+ embedding_dim=self.inner_dim, pooled_projection_dim=pooled_projection_dim
74
+ )
75
+ self.context_embedder = nn.Linear(joint_attention_dim, caption_projection_dim)
76
+
77
+ # `attention_head_dim` is doubled to account for the mixing.
78
+ # It needs to crafted when we get the actual checkpoints.
79
+ self.transformer_blocks = nn.ModuleList(
80
+ [
81
+ JointTransformerBlock(
82
+ dim=self.inner_dim,
83
+ num_attention_heads=num_attention_heads,
84
+ attention_head_dim=self.inner_dim,
85
+ context_pre_only=False,
86
+ )
87
+ for i in range(num_layers)
88
+ ]
89
+ )
90
+
91
+ # controlnet_blocks
92
+ self.controlnet_blocks = nn.ModuleList([])
93
+ for _ in range(len(self.transformer_blocks)):
94
+ controlnet_block = nn.Linear(self.inner_dim, self.inner_dim)
95
+ controlnet_block = zero_module(controlnet_block)
96
+ self.controlnet_blocks.append(controlnet_block)
97
+ pos_embed_input = PatchEmbed(
98
+ height=sample_size,
99
+ width=sample_size,
100
+ patch_size=patch_size,
101
+ in_channels=in_channels,
102
+ embed_dim=self.inner_dim,
103
+ pos_embed_type=None,
104
+ )
105
+ self.pos_embed_input = zero_module(pos_embed_input)
106
+
107
+ self.gradient_checkpointing = False
108
+
109
+ # Copied from diffusers.models.unets.unet_3d_condition.UNet3DConditionModel.enable_forward_chunking
110
+ def enable_forward_chunking(self, chunk_size: Optional[int] = None, dim: int = 0) -> None:
111
+ """
112
+ Sets the attention processor to use [feed forward
113
+ chunking](https://huggingface.co/blog/reformer#2-chunked-feed-forward-layers).
114
+
115
+ Parameters:
116
+ chunk_size (`int`, *optional*):
117
+ The chunk size of the feed-forward layers. If not specified, will run feed-forward layer individually
118
+ over each tensor of dim=`dim`.
119
+ dim (`int`, *optional*, defaults to `0`):
120
+ The dimension over which the feed-forward computation should be chunked. Choose between dim=0 (batch)
121
+ or dim=1 (sequence length).
122
+ """
123
+ if dim not in [0, 1]:
124
+ raise ValueError(f"Make sure to set `dim` to either 0 or 1, not {dim}")
125
+
126
+ # By default chunk size is 1
127
+ chunk_size = chunk_size or 1
128
+
129
+ def fn_recursive_feed_forward(module: torch.nn.Module, chunk_size: int, dim: int):
130
+ if hasattr(module, "set_chunk_feed_forward"):
131
+ module.set_chunk_feed_forward(chunk_size=chunk_size, dim=dim)
132
+
133
+ for child in module.children():
134
+ fn_recursive_feed_forward(child, chunk_size, dim)
135
+
136
+ for module in self.children():
137
+ fn_recursive_feed_forward(module, chunk_size, dim)
138
+
139
+ @property
140
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
141
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
142
+ r"""
143
+ Returns:
144
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
145
+ indexed by its weight name.
146
+ """
147
+ # set recursively
148
+ processors = {}
149
+
150
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
151
+ if hasattr(module, "get_processor"):
152
+ processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
153
+
154
+ for sub_name, child in module.named_children():
155
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
156
+
157
+ return processors
158
+
159
+ for name, module in self.named_children():
160
+ fn_recursive_add_processors(name, module, processors)
161
+
162
+ return processors
163
+
164
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
165
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
166
+ r"""
167
+ Sets the attention processor to use to compute attention.
168
+
169
+ Parameters:
170
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
171
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
172
+ for **all** `Attention` layers.
173
+
174
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
175
+ processor. This is strongly recommended when setting trainable attention processors.
176
+
177
+ """
178
+ count = len(self.attn_processors.keys())
179
+
180
+ if isinstance(processor, dict) and len(processor) != count:
181
+ raise ValueError(
182
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
183
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
184
+ )
185
+
186
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
187
+ if hasattr(module, "set_processor"):
188
+ if not isinstance(processor, dict):
189
+ module.set_processor(processor)
190
+ else:
191
+ module.set_processor(processor.pop(f"{name}.processor"))
192
+
193
+ for sub_name, child in module.named_children():
194
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
195
+
196
+ for name, module in self.named_children():
197
+ fn_recursive_attn_processor(name, module, processor)
198
+
199
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections
200
+ def fuse_qkv_projections(self):
201
+ """
202
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
203
+ are fused. For cross-attention modules, key and value projection matrices are fused.
204
+
205
+ <Tip warning={true}>
206
+
207
+ This API is 🧪 experimental.
208
+
209
+ </Tip>
210
+ """
211
+ self.original_attn_processors = None
212
+
213
+ for _, attn_processor in self.attn_processors.items():
214
+ if "Added" in str(attn_processor.__class__.__name__):
215
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
216
+
217
+ self.original_attn_processors = self.attn_processors
218
+
219
+ for module in self.modules():
220
+ if isinstance(module, Attention):
221
+ module.fuse_projections(fuse=True)
222
+
223
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
224
+ def unfuse_qkv_projections(self):
225
+ """Disables the fused QKV projection if enabled.
226
+
227
+ <Tip warning={true}>
228
+
229
+ This API is 🧪 experimental.
230
+
231
+ </Tip>
232
+
233
+ """
234
+ if self.original_attn_processors is not None:
235
+ self.set_attn_processor(self.original_attn_processors)
236
+
237
+ def _set_gradient_checkpointing(self, module, value=False):
238
+ if hasattr(module, "gradient_checkpointing"):
239
+ module.gradient_checkpointing = value
240
+
241
+ @classmethod
242
+ def from_transformer(cls, transformer, num_layers=None, load_weights_from_transformer=True):
243
+ config = transformer.config
244
+ config["num_layers"] = num_layers or config.num_layers
245
+ controlnet = cls(**config)
246
+
247
+ if load_weights_from_transformer:
248
+ controlnet.pos_embed.load_state_dict(transformer.pos_embed.state_dict(), strict=False)
249
+ controlnet.time_text_embed.load_state_dict(transformer.time_text_embed.state_dict(), strict=False)
250
+ controlnet.context_embedder.load_state_dict(transformer.context_embedder.state_dict(), strict=False)
251
+ controlnet.transformer_blocks.load_state_dict(transformer.transformer_blocks.state_dict())
252
+
253
+ controlnet.pos_embed_input = zero_module(controlnet.pos_embed_input)
254
+
255
+ return controlnet
256
+
257
+ def forward(
258
+ self,
259
+ hidden_states: torch.FloatTensor,
260
+ controlnet_cond: torch.Tensor,
261
+ conditioning_scale: float = 1.0,
262
+ encoder_hidden_states: torch.FloatTensor = None,
263
+ pooled_projections: torch.FloatTensor = None,
264
+ timestep: torch.LongTensor = None,
265
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
266
+ return_dict: bool = True,
267
+ ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
268
+ """
269
+ The [`SD3Transformer2DModel`] forward method.
270
+
271
+ Args:
272
+ hidden_states (`torch.FloatTensor` of shape `(batch size, channel, height, width)`):
273
+ Input `hidden_states`.
274
+ controlnet_cond (`torch.Tensor`):
275
+ The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
276
+ conditioning_scale (`float`, defaults to `1.0`):
277
+ The scale factor for ControlNet outputs.
278
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch size, sequence_len, embed_dims)`):
279
+ Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
280
+ pooled_projections (`torch.FloatTensor` of shape `(batch_size, projection_dim)`): Embeddings projected
281
+ from the embeddings of input conditions.
282
+ timestep ( `torch.LongTensor`):
283
+ Used to indicate denoising step.
284
+ joint_attention_kwargs (`dict`, *optional*):
285
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
286
+ `self.processor` in
287
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
288
+ return_dict (`bool`, *optional*, defaults to `True`):
289
+ Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
290
+ tuple.
291
+
292
+ Returns:
293
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
294
+ `tuple` where the first element is the sample tensor.
295
+ """
296
+ if joint_attention_kwargs is not None:
297
+ joint_attention_kwargs = joint_attention_kwargs.copy()
298
+ lora_scale = joint_attention_kwargs.pop("scale", 1.0)
299
+ else:
300
+ lora_scale = 1.0
301
+
302
+ if USE_PEFT_BACKEND:
303
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
304
+ scale_lora_layers(self, lora_scale)
305
+ else:
306
+ if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
307
+ logger.warning(
308
+ "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
309
+ )
310
+
311
+ height, width = hidden_states.shape[-2:]
312
+
313
+ hidden_states = self.pos_embed(hidden_states) # takes care of adding positional embeddings too.
314
+ temb = self.time_text_embed(timestep, pooled_projections)
315
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
316
+
317
+ # add
318
+ hidden_states = hidden_states + self.pos_embed_input(controlnet_cond)
319
+
320
+ block_res_samples = ()
321
+
322
+ for block in self.transformer_blocks:
323
+ if self.training and self.gradient_checkpointing:
324
+
325
+ def create_custom_forward(module, return_dict=None):
326
+ def custom_forward(*inputs):
327
+ if return_dict is not None:
328
+ return module(*inputs, return_dict=return_dict)
329
+ else:
330
+ return module(*inputs)
331
+
332
+ return custom_forward
333
+
334
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
335
+ hidden_states = torch.utils.checkpoint.checkpoint(
336
+ create_custom_forward(block),
337
+ hidden_states,
338
+ encoder_hidden_states,
339
+ temb,
340
+ **ckpt_kwargs,
341
+ )
342
+
343
+ else:
344
+ encoder_hidden_states, hidden_states = block(
345
+ hidden_states=hidden_states, encoder_hidden_states=encoder_hidden_states, temb=temb
346
+ )
347
+
348
+ block_res_samples = block_res_samples + (hidden_states,)
349
+
350
+ controlnet_block_res_samples = ()
351
+ for block_res_sample, controlnet_block in zip(block_res_samples, self.controlnet_blocks):
352
+ block_res_sample = controlnet_block(block_res_sample)
353
+ controlnet_block_res_samples = controlnet_block_res_samples + (block_res_sample,)
354
+
355
+ # 6. scaling
356
+ controlnet_block_res_samples = [sample * conditioning_scale for sample in controlnet_block_res_samples]
357
+
358
+ if USE_PEFT_BACKEND:
359
+ # remove `lora_scale` from each PEFT layer
360
+ unscale_lora_layers(self, lora_scale)
361
+
362
+ if not return_dict:
363
+ return (controlnet_block_res_samples,)
364
+
365
+ return SD3ControlNetOutput(controlnet_block_samples=controlnet_block_res_samples)
366
+
367
+
368
+ class SD3MultiControlNetModel(ModelMixin):
369
+ r"""
370
+ `SD3ControlNetModel` wrapper class for Multi-SD3ControlNet
371
+
372
+ This module is a wrapper for multiple instances of the `SD3ControlNetModel`. The `forward()` API is designed to be
373
+ compatible with `SD3ControlNetModel`.
374
+
375
+ Args:
376
+ controlnets (`List[SD3ControlNetModel]`):
377
+ Provides additional conditioning to the unet during the denoising process. You must set multiple
378
+ `SD3ControlNetModel` as a list.
379
+ """
380
+
381
+ def __init__(self, controlnets):
382
+ super().__init__()
383
+ self.nets = nn.ModuleList(controlnets)
384
+
385
+ def forward(
386
+ self,
387
+ hidden_states: torch.FloatTensor,
388
+ controlnet_cond: List[torch.tensor],
389
+ conditioning_scale: List[float],
390
+ pooled_projections: torch.FloatTensor,
391
+ encoder_hidden_states: torch.FloatTensor = None,
392
+ timestep: torch.LongTensor = None,
393
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
394
+ return_dict: bool = True,
395
+ ) -> Union[SD3ControlNetOutput, Tuple]:
396
+ for i, (image, scale, controlnet) in enumerate(zip(controlnet_cond, conditioning_scale, self.nets)):
397
+ block_samples = controlnet(
398
+ hidden_states=hidden_states,
399
+ timestep=timestep,
400
+ encoder_hidden_states=encoder_hidden_states,
401
+ pooled_projections=pooled_projections,
402
+ controlnet_cond=image,
403
+ conditioning_scale=scale,
404
+ joint_attention_kwargs=joint_attention_kwargs,
405
+ return_dict=return_dict,
406
+ )
407
+
408
+ # merge samples
409
+ if i == 0:
410
+ control_block_samples = block_samples
411
+ else:
412
+ control_block_samples = [
413
+ control_block_sample + block_sample
414
+ for control_block_sample, block_sample in zip(control_block_samples[0], block_samples[0])
415
+ ]
416
+ control_block_samples = (tuple(control_block_samples),)
417
+
418
+ return control_block_samples
@@ -462,7 +462,7 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
462
462
  device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
463
463
  A map that specifies where each submodule should go. It doesn't need to be defined for each
464
464
  parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the
465
- same device.
465
+ same device. Defaults to `None`, meaning that the model will be loaded on CPU.
466
466
 
467
467
  Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For
468
468
  more information about each option see [designing a device
@@ -774,7 +774,12 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
774
774
  else: # else let accelerate handle loading and dispatching.
775
775
  # Load weights and dispatch according to the device_map
776
776
  # by default the device_map is None and the weights are loaded on the CPU
777
+ force_hook = True
777
778
  device_map = _determine_device_map(model, device_map, max_memory, torch_dtype)
779
+ if device_map is None and is_sharded:
780
+ # we load the parameters on the cpu
781
+ device_map = {"": "cpu"}
782
+ force_hook = False
778
783
  try:
779
784
  accelerate.load_checkpoint_and_dispatch(
780
785
  model,
@@ -784,7 +789,7 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
784
789
  offload_folder=offload_folder,
785
790
  offload_state_dict=offload_state_dict,
786
791
  dtype=torch_dtype,
787
- force_hooks=True,
792
+ force_hooks=force_hook,
788
793
  strict=True,
789
794
  )
790
795
  except AttributeError as e:
@@ -808,12 +813,14 @@ class ModelMixin(torch.nn.Module, PushToHubMixin):
808
813
  model._temp_convert_self_to_deprecated_attention_blocks()
809
814
  accelerate.load_checkpoint_and_dispatch(
810
815
  model,
811
- model_file,
816
+ model_file if not is_sharded else sharded_ckpt_cached_folder,
812
817
  device_map,
813
818
  max_memory=max_memory,
814
819
  offload_folder=offload_folder,
815
820
  offload_state_dict=offload_state_dict,
816
821
  dtype=torch_dtype,
822
+ force_hook=force_hook,
823
+ strict=True,
817
824
  )
818
825
  model._undo_temp_convert_self_to_deprecated_attention_blocks()
819
826
  else:
@@ -30,8 +30,10 @@ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
30
30
 
31
31
 
32
32
  class Transformer2DModelOutput(Transformer2DModelOutput):
33
- deprecation_message = "Importing `Transformer2DModelOutput` from `diffusers.models.transformer_2d` is deprecated and this will be removed in a future version. Please use `from diffusers.models.modeling_outputs import Transformer2DModelOutput`, instead."
34
- deprecate("Transformer2DModelOutput", "1.0.0", deprecation_message)
33
+ def __init__(self, *args, **kwargs):
34
+ deprecation_message = "Importing `Transformer2DModelOutput` from `diffusers.models.transformer_2d` is deprecated and this will be removed in a future version. Please use `from diffusers.models.modeling_outputs import Transformer2DModelOutput`, instead."
35
+ deprecate("Transformer2DModelOutput", "1.0.0", deprecation_message)
36
+ super().__init__(*args, **kwargs)
35
37
 
36
38
 
37
39
  class Transformer2DModel(LegacyModelMixin, LegacyConfigMixin):
@@ -1,4 +1,4 @@
1
- # Copyright 2024 Stability AI and The HuggingFace Team. All rights reserved.
1
+ # Copyright 2024 Stability AI, The HuggingFace Team and The InstantX Team. All rights reserved.
2
2
  #
3
3
  # Licensed under the Apache License, Version 2.0 (the "License");
4
4
  # you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
13
13
  # limitations under the License.
14
14
 
15
15
 
16
- from typing import Any, Dict, Optional, Union
16
+ from typing import Any, Dict, List, Optional, Union
17
17
 
18
18
  import torch
19
19
  import torch.nn as nn
@@ -26,7 +26,7 @@ from ...models.modeling_utils import ModelMixin
26
26
  from ...models.normalization import AdaLayerNormContinuous
27
27
  from ...utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
28
28
  from ..embeddings import CombinedTimestepTextProjEmbeddings, PatchEmbed
29
- from .transformer_2d import Transformer2DModelOutput
29
+ from ..modeling_outputs import Transformer2DModelOutput
30
30
 
31
31
 
32
32
  logger = logging.get_logger(__name__) # pylint: disable=invalid-name
@@ -245,6 +245,7 @@ class SD3Transformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOrigi
245
245
  encoder_hidden_states: torch.FloatTensor = None,
246
246
  pooled_projections: torch.FloatTensor = None,
247
247
  timestep: torch.LongTensor = None,
248
+ block_controlnet_hidden_states: List = None,
248
249
  joint_attention_kwargs: Optional[Dict[str, Any]] = None,
249
250
  return_dict: bool = True,
250
251
  ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
@@ -260,6 +261,8 @@ class SD3Transformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOrigi
260
261
  from the embeddings of input conditions.
261
262
  timestep ( `torch.LongTensor`):
262
263
  Used to indicate denoising step.
264
+ block_controlnet_hidden_states: (`list` of `torch.Tensor`):
265
+ A list of tensors that if specified are added to the residuals of transformer blocks.
263
266
  joint_attention_kwargs (`dict`, *optional*):
264
267
  A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
265
268
  `self.processor` in
@@ -282,9 +285,10 @@ class SD3Transformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOrigi
282
285
  # weight the lora layers by setting `lora_scale` for each PEFT layer
283
286
  scale_lora_layers(self, lora_scale)
284
287
  else:
285
- logger.warning(
286
- "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
287
- )
288
+ if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
289
+ logger.warning(
290
+ "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
291
+ )
288
292
 
289
293
  height, width = hidden_states.shape[-2:]
290
294
 
@@ -292,7 +296,7 @@ class SD3Transformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOrigi
292
296
  temb = self.time_text_embed(timestep, pooled_projections)
293
297
  encoder_hidden_states = self.context_embedder(encoder_hidden_states)
294
298
 
295
- for block in self.transformer_blocks:
299
+ for index_block, block in enumerate(self.transformer_blocks):
296
300
  if self.training and self.gradient_checkpointing:
297
301
 
298
302
  def create_custom_forward(module, return_dict=None):
@@ -305,7 +309,7 @@ class SD3Transformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOrigi
305
309
  return custom_forward
306
310
 
307
311
  ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
308
- hidden_states = torch.utils.checkpoint.checkpoint(
312
+ encoder_hidden_states, hidden_states = torch.utils.checkpoint.checkpoint(
309
313
  create_custom_forward(block),
310
314
  hidden_states,
311
315
  encoder_hidden_states,
@@ -318,6 +322,11 @@ class SD3Transformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOrigi
318
322
  hidden_states=hidden_states, encoder_hidden_states=encoder_hidden_states, temb=temb
319
323
  )
320
324
 
325
+ # controlnet residual
326
+ if block_controlnet_hidden_states is not None and block.context_pre_only is False:
327
+ interval_control = len(self.transformer_blocks) // len(block_controlnet_hidden_states)
328
+ hidden_states = hidden_states + block_controlnet_hidden_states[index_block // interval_control]
329
+
321
330
  hidden_states = self.norm_out(hidden_states, temb)
322
331
  hidden_states = self.proj_out(hidden_states)
323
332
 
@@ -20,6 +20,7 @@ from ..utils import (
20
20
  _dummy_objects = {}
21
21
  _import_structure = {
22
22
  "controlnet": [],
23
+ "controlnet_sd3": [],
23
24
  "controlnet_xs": [],
24
25
  "deprecated": [],
25
26
  "latent_diffusion": [],
@@ -142,6 +143,11 @@ else:
142
143
  "StableDiffusionXLControlNetXSPipeline",
143
144
  ]
144
145
  )
146
+ _import_structure["controlnet_sd3"].extend(
147
+ [
148
+ "StableDiffusion3ControlNetPipeline",
149
+ ]
150
+ )
145
151
  _import_structure["deepfloyd_if"] = [
146
152
  "IFImg2ImgPipeline",
147
153
  "IFImg2ImgSuperResolutionPipeline",
@@ -394,6 +400,9 @@ if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
394
400
  StableDiffusionXLControlNetInpaintPipeline,
395
401
  StableDiffusionXLControlNetPipeline,
396
402
  )
403
+ from .controlnet_sd3 import (
404
+ StableDiffusion3ControlNetPipeline,
405
+ )
397
406
  from .controlnet_xs import (
398
407
  StableDiffusionControlNetXSPipeline,
399
408
  StableDiffusionXLControlNetXSPipeline,
@@ -27,6 +27,7 @@ from .controlnet import (
27
27
  StableDiffusionXLControlNetPipeline,
28
28
  )
29
29
  from .deepfloyd_if import IFImg2ImgPipeline, IFInpaintingPipeline, IFPipeline
30
+ from .hunyuandit import HunyuanDiTPipeline
30
31
  from .kandinsky import (
31
32
  KandinskyCombinedPipeline,
32
33
  KandinskyImg2ImgCombinedPipeline,
@@ -52,6 +53,10 @@ from .stable_diffusion import (
52
53
  StableDiffusionInpaintPipeline,
53
54
  StableDiffusionPipeline,
54
55
  )
56
+ from .stable_diffusion_3 import (
57
+ StableDiffusion3Img2ImgPipeline,
58
+ StableDiffusion3Pipeline,
59
+ )
55
60
  from .stable_diffusion_xl import (
56
61
  StableDiffusionXLImg2ImgPipeline,
57
62
  StableDiffusionXLInpaintPipeline,
@@ -64,7 +69,9 @@ AUTO_TEXT2IMAGE_PIPELINES_MAPPING = OrderedDict(
64
69
  [
65
70
  ("stable-diffusion", StableDiffusionPipeline),
66
71
  ("stable-diffusion-xl", StableDiffusionXLPipeline),
72
+ ("stable-diffusion-3", StableDiffusion3Pipeline),
67
73
  ("if", IFPipeline),
74
+ ("hunyuan", HunyuanDiTPipeline),
68
75
  ("kandinsky", KandinskyCombinedPipeline),
69
76
  ("kandinsky22", KandinskyV22CombinedPipeline),
70
77
  ("kandinsky3", Kandinsky3Pipeline),
@@ -82,6 +89,7 @@ AUTO_IMAGE2IMAGE_PIPELINES_MAPPING = OrderedDict(
82
89
  [
83
90
  ("stable-diffusion", StableDiffusionImg2ImgPipeline),
84
91
  ("stable-diffusion-xl", StableDiffusionXLImg2ImgPipeline),
92
+ ("stable-diffusion-3", StableDiffusion3Img2ImgPipeline),
85
93
  ("if", IFImg2ImgPipeline),
86
94
  ("kandinsky", KandinskyImg2ImgCombinedPipeline),
87
95
  ("kandinsky22", KandinskyV22Img2ImgCombinedPipeline),
@@ -0,0 +1,53 @@
1
+ from typing import TYPE_CHECKING
2
+
3
+ from ...utils import (
4
+ DIFFUSERS_SLOW_IMPORT,
5
+ OptionalDependencyNotAvailable,
6
+ _LazyModule,
7
+ get_objects_from_module,
8
+ is_flax_available,
9
+ is_torch_available,
10
+ is_transformers_available,
11
+ )
12
+
13
+
14
+ _dummy_objects = {}
15
+ _import_structure = {}
16
+
17
+ try:
18
+ if not (is_transformers_available() and is_torch_available()):
19
+ raise OptionalDependencyNotAvailable()
20
+ except OptionalDependencyNotAvailable:
21
+ from ...utils import dummy_torch_and_transformers_objects # noqa F403
22
+
23
+ _dummy_objects.update(get_objects_from_module(dummy_torch_and_transformers_objects))
24
+ else:
25
+ _import_structure["pipeline_stable_diffusion_3_controlnet"] = ["StableDiffusion3ControlNetPipeline"]
26
+
27
+ if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
28
+ try:
29
+ if not (is_transformers_available() and is_torch_available()):
30
+ raise OptionalDependencyNotAvailable()
31
+
32
+ except OptionalDependencyNotAvailable:
33
+ from ...utils.dummy_torch_and_transformers_objects import *
34
+ else:
35
+ from .pipeline_stable_diffusion_3_controlnet import StableDiffusion3ControlNetPipeline
36
+
37
+ try:
38
+ if not (is_transformers_available() and is_flax_available()):
39
+ raise OptionalDependencyNotAvailable()
40
+ except OptionalDependencyNotAvailable:
41
+ from ...utils.dummy_flax_and_transformers_objects import * # noqa F403
42
+
43
+ else:
44
+ import sys
45
+
46
+ sys.modules[__name__] = _LazyModule(
47
+ __name__,
48
+ globals()["__file__"],
49
+ _import_structure,
50
+ module_spec=__spec__,
51
+ )
52
+ for name, value in _dummy_objects.items():
53
+ setattr(sys.modules[__name__], name, value)