Skip to content

Commit 43d2e77

Browse files
committed
More docs and small refactors
1 parent 24e6880 commit 43d2e77

File tree

8 files changed

+140
-97
lines changed

8 files changed

+140
-97
lines changed

docs/source/en/_toctree.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,8 @@
234234
title: Textual Inversion
235235
- local: api/loaders/unet
236236
title: UNet
237+
- local: api/loaders/transformers_sd3
238+
title: SD3Transformer2D
237239
- local: api/loaders/peft
238240
title: PEFT
239241
title: Loaders

docs/source/en/api/attnprocessor.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,5 +53,5 @@ An attention processor is a class for applying different types of attention mech
5353
## AttnProcessorNPU
5454
[[autodoc]] models.attention_processor.AttnProcessorNPU
5555

56-
## IPAdapterJointAttnProcessor2_0
57-
[[autodoc]] models.attention_processor.IPAdapterJointAttnProcessor2_0
56+
## SD3IPAdapterJointAttnProcessor2_0
57+
[[autodoc]] models.attention_processor.SD3IPAdapterJointAttnProcessor2_0
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<!--Copyright 2024 The HuggingFace Team. All rights reserved.
2+
3+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4+
the License. You may obtain a copy of the License at
5+
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
8+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10+
specific language governing permissions and limitations under the License.
11+
-->
12+
13+
# SD3Transformer2D
14+
15+
This class is useful when *only* loading weights into a [`SD3Transformer2DModel`]. If you need to load weights into the text encoder or a text encoder and SD3Transformer2DModel, check [`SD3LoraLoaderMixin`](lora#diffusers.loaders.SD3LoraLoaderMixin) class instead.
16+
17+
The [`SD3Transformer2DLoadersMixin`] class currently only loads IP-Adapter weights, but will be used in the future to save weights and load LoRAs.
18+
19+
<Tip>
20+
21+
To learn more about how to load LoRA weights, see the [LoRA](../../using-diffusers/loading_adapters#lora) loading guide.
22+
23+
</Tip>
24+
25+
## SD3Transformer2DLoadersMixin
26+
27+
[[autodoc]] loaders.transformers_sd3.SD3Transformer2DLoadersMixin
28+
- all
29+
- _load_ip_adapter_weights

src/diffusers/loaders/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ def text_encoder_attn_modules(text_encoder):
5656
if is_torch_available():
5757
_import_structure["single_file_model"] = ["FromOriginalModelMixin"]
5858

59+
_import_structure["transformers_sd3"] = ["SD3Transformer2DLoadersMixin"]
5960
_import_structure["unet"] = ["UNet2DConditionLoadersMixin"]
6061
_import_structure["utils"] = ["AttnProcsLayers"]
6162
if is_transformers_available():
@@ -82,6 +83,7 @@ def text_encoder_attn_modules(text_encoder):
8283
if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
8384
if is_torch_available():
8485
from .single_file_model import FromOriginalModelMixin
86+
from .transformers_sd3 import SD3Transformer2DLoadersMixin
8587
from .unet import UNet2DConditionLoadersMixin
8688
from .utils import AttnProcsLayers
8789

src/diffusers/loaders/ip_adapter.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,9 @@
4040
AttnProcessor2_0,
4141
IPAdapterAttnProcessor,
4242
IPAdapterAttnProcessor2_0,
43-
IPAdapterJointAttnProcessor2_0,
4443
IPAdapterXFormersAttnProcessor,
4544
JointAttnProcessor2_0,
45+
SD3IPAdapterJointAttnProcessor2_0,
4646
)
4747

4848

@@ -369,7 +369,7 @@ def is_ip_adapter_active(self) -> bool:
369369
scales = [
370370
attn_proc.scale
371371
for attn_proc in self.transformer.attn_processors.values()
372-
if isinstance(attn_proc, IPAdapterJointAttnProcessor2_0)
372+
if isinstance(attn_proc, SD3IPAdapterJointAttnProcessor2_0)
373373
]
374374

375375
return len(scales) > 0 and any(scale > 0 for scale in scales)
@@ -379,7 +379,7 @@ def load_ip_adapter(
379379
self,
380380
pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
381381
subfolder: str,
382-
weight_name: str,
382+
weight_name: str = "ip-adapter.safetensors",
383383
image_encoder_folder: Optional[str] = "image_encoder",
384384
**kwargs,
385385
) -> None:
@@ -396,7 +396,7 @@ def load_ip_adapter(
396396
subfolder (`str`):
397397
The subfolder location of a model file within a larger model repository on the Hub or locally. If a
398398
list is passed, it should have the same length as `weight_name`.
399-
weight_name (`str`):
399+
weight_name (`str`, defaults to "ip-adapter.safetensors"):
400400
The name of the weight file to load. If a list is passed, it should have the same length as
401401
`subfolder`.
402402
image_encoder_folder (`str`, *optional*, defaults to `image_encoder`):
@@ -547,7 +547,7 @@ def set_ip_adapter_scale(self, scale: float) -> None:
547547
548548
"""
549549
for attn_processor in self.transformer.attn_processors.values():
550-
if isinstance(attn_processor, IPAdapterJointAttnProcessor2_0):
550+
if isinstance(attn_processor, SD3IPAdapterJointAttnProcessor2_0):
551551
attn_processor.scale = scale
552552

553553
def unload_ip_adapter(self) -> None:
@@ -577,7 +577,9 @@ def unload_ip_adapter(self) -> None:
577577

578578
# Restore original attention processors layers
579579
attn_procs = {
580-
name: (JointAttnProcessor2_0() if isinstance(value, IPAdapterJointAttnProcessor2_0) else value.__class__())
580+
name: (
581+
JointAttnProcessor2_0() if isinstance(value, SD3IPAdapterJointAttnProcessor2_0) else value.__class__()
582+
)
581583
for name, value in self.transformer.attn_processors.items()
582584
}
583585
self.transformer.set_attn_processor(attn_procs)
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
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+
from typing import Dict
15+
16+
from ..models.attention_processor import SD3IPAdapterJointAttnProcessor2_0
17+
from ..models.embeddings import IPAdapterTimeImageProjection
18+
from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT, load_model_dict_into_meta
19+
20+
21+
class SD3Transformer2DLoadersMixin:
22+
"""Load IP-Adapters and LoRA layers into a `[SD3Transformer2DModel]`."""
23+
24+
def _load_ip_adapter_weights(self, state_dict: Dict, low_cpu_mem_usage: bool = _LOW_CPU_MEM_USAGE_DEFAULT) -> None:
25+
"""Sets IP-Adapter attention processors, image projection, and loads state_dict.
26+
27+
Args:
28+
state_dict (`Dict`):
29+
State dict with keys "ip_adapter", which contains parameters for attention processors, and
30+
"image_proj", which contains parameters for image projection net.
31+
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
32+
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
33+
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
34+
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
35+
argument to `True` will raise an error.
36+
"""
37+
# IP-Adapter cross attention parameters
38+
hidden_size = self.config.attention_head_dim * self.config.num_attention_heads
39+
ip_hidden_states_dim = self.config.attention_head_dim * self.config.num_attention_heads
40+
timesteps_emb_dim = state_dict["ip_adapter"]["0.norm_ip.linear.weight"].shape[1]
41+
42+
# Dict where key is transformer layer index, value is attention processor's state dict
43+
# ip_adapter state dict keys example: "0.norm_ip.linear.weight"
44+
layer_state_dict = {idx: {} for idx in range(len(self.attn_processors))}
45+
for key, weights in state_dict["ip_adapter"].items():
46+
idx, name = key.split(".", maxsplit=1)
47+
layer_state_dict[int(idx)][name] = weights
48+
49+
# Create IP-Adapter attention processor
50+
attn_procs = {}
51+
for idx, name in enumerate(self.attn_processors.keys()):
52+
attn_procs[name] = SD3IPAdapterJointAttnProcessor2_0(
53+
hidden_size=hidden_size,
54+
ip_hidden_states_dim=ip_hidden_states_dim,
55+
head_dim=self.config.attention_head_dim,
56+
timesteps_emb_dim=timesteps_emb_dim,
57+
).to(self.device, dtype=self.dtype)
58+
59+
if not low_cpu_mem_usage:
60+
attn_procs[name].load_state_dict(layer_state_dict[idx], strict=True)
61+
else:
62+
load_model_dict_into_meta(
63+
attn_procs[name], layer_state_dict[idx], device=self.device, dtype=self.dtype
64+
)
65+
66+
self.set_attn_processor(attn_procs)
67+
68+
# Image projetion parameters
69+
embed_dim = state_dict["image_proj"]["proj_in.weight"].shape[1]
70+
output_dim = state_dict["image_proj"]["proj_out.weight"].shape[0]
71+
hidden_dim = state_dict["image_proj"]["proj_in.weight"].shape[0]
72+
heads = state_dict["image_proj"]["layers.0.attn.to_q.weight"].shape[0] // 64
73+
num_queries = state_dict["image_proj"]["latents"].shape[1]
74+
timestep_in_dim = state_dict["image_proj"]["time_embedding.linear_1.weight"].shape[1]
75+
76+
# Image projection
77+
self.image_proj = IPAdapterTimeImageProjection(
78+
embed_dim=embed_dim,
79+
output_dim=output_dim,
80+
hidden_dim=hidden_dim,
81+
heads=heads,
82+
num_queries=num_queries,
83+
timestep_in_dim=timestep_in_dim,
84+
).to(device=self.device, dtype=self.dtype)
85+
86+
if not low_cpu_mem_usage:
87+
self.image_proj.load_state_dict(state_dict, strict=True)
88+
else:
89+
load_model_dict_into_meta(self.image_proj, state_dict, device=self.device, dtype=self.dtype)

src/diffusers/models/attention_processor.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5160,7 +5160,7 @@ def __call__(
51605160
return hidden_states
51615161

51625162

5163-
class IPAdapterJointAttnProcessor2_0(torch.nn.Module):
5163+
class SD3IPAdapterJointAttnProcessor2_0(torch.nn.Module):
51645164
"""
51655165
Attention processor for IP-Adapter used typically in processing the SD3-like self-attention projections, with
51665166
additional image-based information and timestep embeddings.
@@ -5844,7 +5844,7 @@ def __call__(
58445844
IPAdapterAttnProcessor,
58455845
IPAdapterAttnProcessor2_0,
58465846
IPAdapterXFormersAttnProcessor,
5847-
IPAdapterJointAttnProcessor2_0,
5847+
SD3IPAdapterJointAttnProcessor2_0,
58485848
PAGIdentitySelfAttnProcessor2_0,
58495849
PAGCFGIdentitySelfAttnProcessor2_0,
58505850
LoRAAttnProcessor,

src/diffusers/models/transformers/transformer_sd3.py

Lines changed: 6 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -19,19 +19,19 @@
1919

2020
from ...configuration_utils import ConfigMixin, register_to_config
2121
from ...loaders import FromOriginalModelMixin, PeftAdapterMixin
22+
from ...loaders.transformers_sd3 import SD3Transformer2DLoadersMixin
2223
from ...models.attention import FeedForward, JointTransformerBlock
2324
from ...models.attention_processor import (
2425
Attention,
2526
AttentionProcessor,
2627
FusedJointAttnProcessor2_0,
27-
IPAdapterJointAttnProcessor2_0,
2828
JointAttnProcessor2_0,
2929
)
30-
from ...models.modeling_utils import ModelMixin, load_model_dict_into_meta
30+
from ...models.modeling_utils import ModelMixin
3131
from ...models.normalization import AdaLayerNormContinuous, AdaLayerNormZero
3232
from ...utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
3333
from ...utils.torch_utils import maybe_allow_in_graph
34-
from ..embeddings import CombinedTimestepTextProjEmbeddings, IPAdapterTimeImageProjection, PatchEmbed
34+
from ..embeddings import CombinedTimestepTextProjEmbeddings, PatchEmbed
3535
from ..modeling_outputs import Transformer2DModelOutput
3636

3737

@@ -104,7 +104,9 @@ def forward(self, hidden_states: torch.Tensor, temb: torch.Tensor):
104104
return hidden_states
105105

106106

107-
class SD3Transformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
107+
class SD3Transformer2DModel(
108+
ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin, SD3Transformer2DLoadersMixin
109+
):
108110
"""
109111
The Transformer model introduced in Stable Diffusion 3.
110112
@@ -331,89 +333,6 @@ def _set_gradient_checkpointing(self, module, value=False):
331333
if hasattr(module, "gradient_checkpointing"):
332334
module.gradient_checkpointing = value
333335

334-
def _load_ip_adapter_weights(self, state_dict: Dict, low_cpu_mem_usage: bool) -> None:
335-
"""Sets IP-Adapter attention processors, image projection, and loads state_dict.
336-
337-
Args:
338-
state_dict (`Dict`):
339-
PyTorch state dict with keys "ip_adapter", which contains parameters for attention processors, and
340-
"image_proj", which contains parameters for image projection net.
341-
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
342-
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
343-
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
344-
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
345-
argument to `True` will raise an error.
346-
"""
347-
# IP-Adapter cross attention parameters
348-
hidden_size = self.config.attention_head_dim * self.config.num_attention_heads
349-
ip_hidden_states_dim = self.config.attention_head_dim * self.config.num_attention_heads
350-
timesteps_emb_dim = state_dict["ip_adapter"]["0.norm_ip.linear.weight"].shape[1]
351-
352-
# Dict where key is transformer layer index, value is attention processor's state dict
353-
# ip_adapter state dict keys example: "0.norm_ip.linear.weight"
354-
layer_state_dict = {idx: {} for idx in range(len(self.attn_processors))}
355-
for key, weights in state_dict["ip_adapter"].items():
356-
idx, name = key.split(".", maxsplit=1)
357-
layer_state_dict[int(idx)][name] = weights
358-
359-
# Create IP-Adapter attention processor
360-
attn_procs = {}
361-
for idx, name in enumerate(self.attn_processors.keys()):
362-
attn_procs[name] = IPAdapterJointAttnProcessor2_0(
363-
hidden_size=hidden_size,
364-
ip_hidden_states_dim=ip_hidden_states_dim,
365-
head_dim=self.config.attention_head_dim,
366-
timesteps_emb_dim=timesteps_emb_dim,
367-
).to(self.device, dtype=self.dtype)
368-
369-
if not low_cpu_mem_usage:
370-
attn_procs[name].load_state_dict(layer_state_dict[idx], strict=True)
371-
else:
372-
load_model_dict_into_meta(
373-
attn_procs[name], layer_state_dict[idx], device=self.device, dtype=self.dtype
374-
)
375-
376-
self.set_attn_processor(attn_procs)
377-
378-
# Convert image_proj state dict to diffusers
379-
image_proj_state_dict = {}
380-
for key, value in state_dict["image_proj"].items():
381-
if key.startswith("layers."):
382-
idx = key.split(".")[1]
383-
key = key.replace(f"layers.{idx}.0.norm1", f"layers.{idx}.ln0")
384-
key = key.replace(f"layers.{idx}.0.norm2", f"layers.{idx}.ln1")
385-
key = key.replace(f"layers.{idx}.0.to_q", f"layers.{idx}.attn.to_q")
386-
key = key.replace(f"layers.{idx}.0.to_kv", f"layers.{idx}.attn.to_kv")
387-
key = key.replace(f"layers.{idx}.0.to_out", f"layers.{idx}.attn.to_out.0")
388-
key = key.replace(f"layers.{idx}.1.0", f"layers.{idx}.adaln_norm")
389-
key = key.replace(f"layers.{idx}.1.1", f"layers.{idx}.ff.net.0.proj")
390-
key = key.replace(f"layers.{idx}.1.3", f"layers.{idx}.ff.net.2")
391-
key = key.replace(f"layers.{idx}.2.1", f"layers.{idx}.adaln_proj")
392-
image_proj_state_dict[key] = value
393-
394-
# Image projetion parameters
395-
embed_dim = image_proj_state_dict["proj_in.weight"].shape[1]
396-
output_dim = image_proj_state_dict["proj_out.weight"].shape[0]
397-
hidden_dim = image_proj_state_dict["proj_in.weight"].shape[0]
398-
heads = image_proj_state_dict["layers.0.attn.to_q.weight"].shape[0] // 64
399-
num_queries = image_proj_state_dict["latents"].shape[1]
400-
timestep_in_dim = image_proj_state_dict["time_embedding.linear_1.weight"].shape[1]
401-
402-
# Image projection
403-
self.image_proj = IPAdapterTimeImageProjection(
404-
embed_dim=embed_dim,
405-
output_dim=output_dim,
406-
hidden_dim=hidden_dim,
407-
heads=heads,
408-
num_queries=num_queries,
409-
timestep_in_dim=timestep_in_dim,
410-
).to(device=self.device, dtype=self.dtype)
411-
412-
if not low_cpu_mem_usage:
413-
self.image_proj.load_state_dict(image_proj_state_dict, strict=True)
414-
else:
415-
load_model_dict_into_meta(self.image_proj, image_proj_state_dict, device=self.device, dtype=self.dtype)
416-
417336
def forward(
418337
self,
419338
hidden_states: torch.FloatTensor,

0 commit comments

Comments
 (0)