Diffusers
Safetensors
BiliSakura commited on
Commit
acccad2
·
verified ·
1 Parent(s): c5cfae9

Upload folder using huggingface_hub

Browse files
__pycache__/pipeline_utils.cpython-312.pyc ADDED
Binary file (5.07 kB). View file
 
convert_inverse_renderer_1024.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Convert GilgameshYX InverseRenderer-1024 into BiliSakura IntrisicWeather-diffusers layout."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import shutil
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from diffusers.models.transformers import SD3Transformer2DModel
12
+
13
+ COLLECTION_ROOT = Path(__file__).resolve().parent
14
+ INTRINSIC_REPO = Path("/data/projects/IntrinsicWeather-diffusers")
15
+ sys.path.insert(0, str(INTRINSIC_REPO / "src"))
16
+ sys.path.insert(0, str(INTRINSIC_REPO))
17
+
18
+ from intrinsic_weather.models.transformers.transformer_intrinsic_weather import ( # noqa: E402
19
+ IntrinsicWeatherSD3Transformer2DModel,
20
+ )
21
+ from scripts._conversion_utils import ( # noqa: E402
22
+ ROOT as REPO_ROOT,
23
+ expand_sd3_input_projection,
24
+ merge_sharded_state_dict,
25
+ save_imaa_bundle,
26
+ write_scheduler_config,
27
+ )
28
+
29
+ SD3_PATH = Path(
30
+ "/data/projects/Visual-Generative-Foundation-Model-Collection/models/stabilityai/stable-diffusion-3-medium-diffusers"
31
+ )
32
+ SD35_TRANSFORMER_REPO = "stabilityai/stable-diffusion-3.5-medium"
33
+ CKPT_PATH = Path(
34
+ "/data/projects/Visual-Generative-Foundation-Model-Collection/models/GilgameshYX/InverseRenderer-1024"
35
+ )
36
+ OUTPUT_ROOT = COLLECTION_ROOT
37
+ TRANSFORMER_VARIANT = "inverse-1024"
38
+ SHARED_COMPONENTS = (
39
+ "text_encoder",
40
+ "text_encoder_2",
41
+ "text_encoder_3",
42
+ "tokenizer",
43
+ "tokenizer_2",
44
+ "tokenizer_3",
45
+ "vae",
46
+ "scheduler",
47
+ )
48
+
49
+
50
+ def copy_sd3_shared_components(sd3_path: Path, output_path: Path) -> None:
51
+ for name in SHARED_COMPONENTS:
52
+ src = sd3_path / name
53
+ dst = output_path / name
54
+ if dst.exists():
55
+ print(f"Skipping existing shared component: {dst}")
56
+ continue
57
+ print(f"Copying {name} ...")
58
+ shutil.copytree(src, dst)
59
+
60
+
61
+ def main() -> None:
62
+ transformer_dir = OUTPUT_ROOT / "transformer" / TRANSFORMER_VARIANT
63
+ transformer_dir.mkdir(parents=True, exist_ok=True)
64
+
65
+ print(f"Ensuring shared SD3 components from {SD3_PATH} ...")
66
+ copy_sd3_shared_components(SD3_PATH, OUTPUT_ROOT)
67
+ write_scheduler_config(OUTPUT_ROOT)
68
+
69
+ print("Converting inverse renderer transformer (1024) ...")
70
+ base_transformer = SD3Transformer2DModel.from_config(
71
+ SD3Transformer2DModel.load_config(SD35_TRANSFORMER_REPO, subfolder="transformer")
72
+ )
73
+ base_transformer = expand_sd3_input_projection(base_transformer, in_channels=32)
74
+ custom_blocks = IntrinsicWeatherSD3Transformer2DModel.from_config(base_transformer.config)
75
+ custom_blocks.load_state_dict(
76
+ merge_sharded_state_dict(
77
+ [
78
+ CKPT_PATH / "pytorch_model-00001-of-00002.bin",
79
+ CKPT_PATH / "pytorch_model-00002-of-00002.bin",
80
+ ]
81
+ ),
82
+ strict=True,
83
+ )
84
+ custom_blocks.save_pretrained(transformer_dir.as_posix(), safe_serialization=True)
85
+ shutil.copy2(
86
+ REPO_ROOT / "src" / "intrinsic_weather" / "models" / "transformers" / "transformer_intrinsic_weather.py",
87
+ transformer_dir / "transformer_intrinsic_weather.py",
88
+ )
89
+
90
+ print("Saving IMAA weights from InverseRenderer-1024 ...")
91
+ save_imaa_bundle(CKPT_PATH / "imaa.pth", OUTPUT_ROOT, safe_serialization=True)
92
+
93
+ conversion_metadata = {
94
+ "task": "inverse_renderer",
95
+ "resolution": 1024,
96
+ "transformer_variant": TRANSFORMER_VARIANT,
97
+ "source_transformer_checkpoints": [
98
+ str((CKPT_PATH / "pytorch_model-00001-of-00002.bin").resolve()),
99
+ str((CKPT_PATH / "pytorch_model-00002-of-00002.bin").resolve()),
100
+ ],
101
+ "source_imaa_checkpoint": str((CKPT_PATH / "imaa.pth").resolve()),
102
+ "sd3_path": str(SD3_PATH.resolve()),
103
+ "sd35_transformer_repo": SD35_TRANSFORMER_REPO,
104
+ "in_channels": 32,
105
+ }
106
+ (OUTPUT_ROOT / "conversion_metadata_inverse_1024.json").write_text(
107
+ json.dumps(conversion_metadata, indent=2) + "\n",
108
+ encoding="utf-8",
109
+ )
110
+ print(f"Saved transformer to: {transformer_dir}")
111
+ print("Load with: load_inverse_pipeline(transformer_subfolder='inverse-1024')")
112
+
113
+
114
+ if __name__ == "__main__":
115
+ main()
imaa/__pycache__/imaa.cpython-312.pyc ADDED
Binary file (10.5 kB). View file
 
imaa/imaa.py CHANGED
@@ -46,7 +46,7 @@ def extract_patch_tokens_min_windows(
46
  token_avgs = []
47
 
48
  for batch_idx in range(batch_size):
49
- image = images[batch_idx].float()
50
  if image.max() <= 1.0:
51
  image_np = (image.permute(1, 2, 0).cpu().numpy() * 255).clip(0, 255).astype("uint8")
52
  else:
 
46
  token_avgs = []
47
 
48
  for batch_idx in range(batch_size):
49
+ image = images[batch_idx]
50
  if image.max() <= 1.0:
51
  image_np = (image.permute(1, 2, 0).cpu().numpy() * 255).clip(0, 255).astype("uint8")
52
  else:
transformer/inverse-1024/__pycache__/transformer_intrinsic_weather.cpython-312.pyc ADDED
Binary file (55.8 kB). View file
 
transformer/inverse-1024/config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "IntrinsicWeatherSD3Transformer2DModel",
3
+ "_diffusers_version": "0.38.0",
4
+ "attention_head_dim": 64,
5
+ "caption_projection_dim": 1536,
6
+ "dual_attention_layers": [
7
+ 0,
8
+ 1,
9
+ 2,
10
+ 3,
11
+ 4,
12
+ 5,
13
+ 6,
14
+ 7,
15
+ 8,
16
+ 9,
17
+ 10,
18
+ 11,
19
+ 12
20
+ ],
21
+ "in_channels": 32,
22
+ "joint_attention_dim": 4096,
23
+ "num_attention_heads": 24,
24
+ "num_layers": 24,
25
+ "out_channels": 16,
26
+ "patch_size": 2,
27
+ "pooled_projection_dim": 2048,
28
+ "pos_embed_max_size": 384,
29
+ "qk_norm": "rms_norm",
30
+ "sample_size": 128
31
+ }
transformer/inverse-1024/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e588327aee089a32caf775fb28437c0e544f5b9b9fec52feb1cf5a9ad26acb01
3
+ size 9879154080
transformer/inverse-1024/transformer_intrinsic_weather.py ADDED
@@ -0,0 +1,1527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from __future__ import annotations
15
+
16
+ import inspect
17
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+ from torch import nn as torch_nn
24
+
25
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
26
+ from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin, SD3Transformer2DLoadersMixin
27
+ from diffusers.models.attention import FeedForward, JointTransformerBlock, _chunked_feed_forward
28
+ from diffusers.models.attention_processor import (
29
+ Attention,
30
+ AttentionProcessor,
31
+ AttnProcessor,
32
+ AttnProcessor2_0,
33
+ FusedJointAttnProcessor2_0,
34
+ JointAttnProcessor2_0,
35
+ SpatialNorm,
36
+ )
37
+ from diffusers.models.embeddings import CombinedTimestepTextProjEmbeddings, PatchEmbed, SinusoidalPositionalEmbedding
38
+ from diffusers.models.modeling_outputs import Transformer2DModelOutput
39
+ from diffusers.models.modeling_utils import ModelMixin
40
+ from diffusers.models.normalization import (
41
+ AdaLayerNorm,
42
+ AdaLayerNormContinuous,
43
+ AdaLayerNormZero,
44
+ RMSNorm,
45
+ SD35AdaLayerNormZeroX,
46
+ )
47
+ from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
48
+ from diffusers.utils.torch_utils import maybe_allow_in_graph
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+
53
+ class MapAwareAttention(nn.Module):
54
+ r"""
55
+ A cross attention layer.
56
+
57
+ Parameters:
58
+ query_dim (`int`):
59
+ The number of channels in the query.
60
+ cross_attention_dim (`int`, *optional*):
61
+ The number of channels in the encoder_hidden_states. If not given, defaults to `query_dim`.
62
+ heads (`int`, *optional*, defaults to 8):
63
+ The number of heads to use for multi-head attention.
64
+ kv_heads (`int`, *optional*, defaults to `None`):
65
+ The number of key and value heads to use for multi-head attention. Defaults to `heads`. If
66
+ `kv_heads=heads`, the model will use Multi Head Attention (MHA), if `kv_heads=1` the model will use Multi
67
+ Query Attention (MQA) otherwise GQA is used.
68
+ dim_head (`int`, *optional*, defaults to 64):
69
+ The number of channels in each head.
70
+ dropout (`float`, *optional*, defaults to 0.0):
71
+ The dropout probability to use.
72
+ bias (`bool`, *optional*, defaults to False):
73
+ Set to `True` for the query, key, and value linear layers to contain a bias parameter.
74
+ upcast_attention (`bool`, *optional*, defaults to False):
75
+ Set to `True` to upcast the attention computation to `float32`.
76
+ upcast_softmax (`bool`, *optional*, defaults to False):
77
+ Set to `True` to upcast the softmax computation to `float32`.
78
+ cross_attention_norm (`str`, *optional*, defaults to `None`):
79
+ The type of normalization to use for the cross attention. Can be `None`, `layer_norm`, or `group_norm`.
80
+ cross_attention_norm_num_groups (`int`, *optional*, defaults to 32):
81
+ The number of groups to use for the group norm in the cross attention.
82
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
83
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
84
+ norm_num_groups (`int`, *optional*, defaults to `None`):
85
+ The number of groups to use for the group norm in the attention.
86
+ spatial_norm_dim (`int`, *optional*, defaults to `None`):
87
+ The number of channels to use for the spatial normalization.
88
+ out_bias (`bool`, *optional*, defaults to `True`):
89
+ Set to `True` to use a bias in the output linear layer.
90
+ scale_qk (`bool`, *optional*, defaults to `True`):
91
+ Set to `True` to scale the query and key by `1 / sqrt(dim_head)`.
92
+ only_cross_attention (`bool`, *optional*, defaults to `False`):
93
+ Set to `True` to only use cross attention and not added_kv_proj_dim. Can only be set to `True` if
94
+ `added_kv_proj_dim` is not `None`.
95
+ eps (`float`, *optional*, defaults to 1e-5):
96
+ An additional value added to the denominator in group normalization that is used for numerical stability.
97
+ rescale_output_factor (`float`, *optional*, defaults to 1.0):
98
+ A factor to rescale the output by dividing it with this value.
99
+ residual_connection (`bool`, *optional*, defaults to `False`):
100
+ Set to `True` to add the residual connection to the output.
101
+ _from_deprecated_attn_block (`bool`, *optional*, defaults to `False`):
102
+ Set to `True` if the attention block is loaded from a deprecated state dict.
103
+ processor (`AttnProcessor`, *optional*, defaults to `None`):
104
+ The attention processor to use. If `None`, defaults to `AttnProcessor2_0` if `torch 2.x` is used and
105
+ `AttnProcessor` otherwise.
106
+ """
107
+
108
+ def __init__(
109
+ self,
110
+ query_dim: int,
111
+ cross_attention_dim: Optional[int] = None,
112
+ heads: int = 8,
113
+ kv_heads: Optional[int] = None,
114
+ dim_head: int = 64,
115
+ dropout: float = 0.0,
116
+ bias: bool = False,
117
+ upcast_attention: bool = False,
118
+ upcast_softmax: bool = False,
119
+ cross_attention_norm: Optional[str] = None,
120
+ cross_attention_norm_num_groups: int = 32,
121
+ qk_norm: Optional[str] = None,
122
+ added_kv_proj_dim: Optional[int] = None,
123
+ added_proj_bias: Optional[bool] = True,
124
+ norm_num_groups: Optional[int] = None,
125
+ spatial_norm_dim: Optional[int] = None,
126
+ out_bias: bool = True,
127
+ scale_qk: bool = True,
128
+ only_cross_attention: bool = False,
129
+ eps: float = 1e-5,
130
+ rescale_output_factor: float = 1.0,
131
+ residual_connection: bool = False,
132
+ _from_deprecated_attn_block: bool = False,
133
+ processor: Optional["AttnProcessor"] = None,
134
+ out_dim: int = None,
135
+ out_context_dim: int = None,
136
+ context_pre_only=None,
137
+ pre_only=False,
138
+ elementwise_affine: bool = True,
139
+ is_causal: bool = False,
140
+ ):
141
+ super().__init__()
142
+
143
+ # To prevent circular import.
144
+ from diffusers.models.normalization import FP32LayerNorm, LpNorm, RMSNorm
145
+
146
+ self.inner_dim = out_dim if out_dim is not None else dim_head * heads
147
+ self.inner_kv_dim = self.inner_dim if kv_heads is None else dim_head * kv_heads
148
+ self.query_dim = query_dim
149
+ self.use_bias = bias
150
+ self.is_cross_attention = cross_attention_dim is not None
151
+ self.cross_attention_dim = cross_attention_dim if cross_attention_dim is not None else query_dim
152
+ self.upcast_attention = upcast_attention
153
+ self.upcast_softmax = upcast_softmax
154
+ self.rescale_output_factor = rescale_output_factor
155
+ self.residual_connection = residual_connection
156
+ self.dropout = dropout
157
+ self.fused_projections = False
158
+ self.out_dim = out_dim if out_dim is not None else query_dim
159
+ self.out_context_dim = out_context_dim if out_context_dim is not None else query_dim
160
+ self.context_pre_only = context_pre_only
161
+ self.pre_only = pre_only
162
+ self.is_causal = is_causal
163
+
164
+ # we make use of this private variable to know whether this class is loaded
165
+ # with an deprecated state dict so that we can convert it on the fly
166
+ self._from_deprecated_attn_block = _from_deprecated_attn_block
167
+
168
+ self.scale_qk = scale_qk
169
+ self.scale = dim_head**-0.5 if self.scale_qk else 1.0
170
+
171
+ self.heads = out_dim // dim_head if out_dim is not None else heads
172
+ # for slice_size > 0 the attention score computation
173
+ # is split across the batch axis to save memory
174
+ # You can set slice_size with `set_attention_slice`
175
+ self.sliceable_head_dim = heads
176
+
177
+ self.added_kv_proj_dim = added_kv_proj_dim
178
+ self.only_cross_attention = only_cross_attention
179
+
180
+ if self.added_kv_proj_dim is None and self.only_cross_attention:
181
+ raise ValueError(
182
+ "`only_cross_attention` can only be set to True if `added_kv_proj_dim` is not None. Make sure to set either `only_cross_attention=False` or define `added_kv_proj_dim`."
183
+ )
184
+
185
+ if norm_num_groups is not None:
186
+ self.group_norm = nn.GroupNorm(num_channels=query_dim, num_groups=norm_num_groups, eps=eps, affine=True)
187
+ else:
188
+ self.group_norm = None
189
+
190
+ if spatial_norm_dim is not None:
191
+ self.spatial_norm = SpatialNorm(f_channels=query_dim, zq_channels=spatial_norm_dim)
192
+ else:
193
+ self.spatial_norm = None
194
+
195
+ if qk_norm is None:
196
+ self.norm_q = None
197
+ self.norm_k = None
198
+ elif qk_norm == "layer_norm":
199
+ self.norm_q = nn.LayerNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
200
+ self.norm_k = nn.LayerNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
201
+ elif qk_norm == "fp32_layer_norm":
202
+ self.norm_q = FP32LayerNorm(dim_head, elementwise_affine=False, bias=False, eps=eps)
203
+ self.norm_k = FP32LayerNorm(dim_head, elementwise_affine=False, bias=False, eps=eps)
204
+ elif qk_norm == "layer_norm_across_heads":
205
+ # Lumina applies qk norm across all heads
206
+ self.norm_q = nn.LayerNorm(dim_head * heads, eps=eps)
207
+ self.norm_k = nn.LayerNorm(dim_head * kv_heads, eps=eps)
208
+ elif qk_norm == "rms_norm":
209
+ self.norm_q = RMSNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
210
+ self.norm_k = RMSNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
211
+ elif qk_norm == "rms_norm_across_heads":
212
+ # LTX applies qk norm across all heads
213
+ self.norm_q = RMSNorm(dim_head * heads, eps=eps)
214
+ self.norm_k = RMSNorm(dim_head * kv_heads, eps=eps)
215
+ elif qk_norm == "l2":
216
+ self.norm_q = LpNorm(p=2, dim=-1, eps=eps)
217
+ self.norm_k = LpNorm(p=2, dim=-1, eps=eps)
218
+ else:
219
+ raise ValueError(
220
+ f"unknown qk_norm: {qk_norm}. Should be one of None, 'layer_norm', 'fp32_layer_norm', 'layer_norm_across_heads', 'rms_norm', 'rms_norm_across_heads', 'l2'."
221
+ )
222
+
223
+ if cross_attention_norm is None:
224
+ self.norm_cross = None
225
+ elif cross_attention_norm == "layer_norm":
226
+ self.norm_cross = nn.LayerNorm(self.cross_attention_dim)
227
+ elif cross_attention_norm == "group_norm":
228
+ if self.added_kv_proj_dim is not None:
229
+ # The given `encoder_hidden_states` are initially of shape
230
+ # (batch_size, seq_len, added_kv_proj_dim) before being projected
231
+ # to (batch_size, seq_len, cross_attention_dim). The norm is applied
232
+ # before the projection, so we need to use `added_kv_proj_dim` as
233
+ # the number of channels for the group norm.
234
+ norm_cross_num_channels = added_kv_proj_dim
235
+ else:
236
+ norm_cross_num_channels = self.cross_attention_dim
237
+
238
+ self.norm_cross = nn.GroupNorm(
239
+ num_channels=norm_cross_num_channels, num_groups=cross_attention_norm_num_groups, eps=1e-5, affine=True
240
+ )
241
+ else:
242
+ raise ValueError(
243
+ f"unknown cross_attention_norm: {cross_attention_norm}. Should be None, 'layer_norm' or 'group_norm'"
244
+ )
245
+
246
+ self.to_q = nn.Linear(query_dim, self.inner_dim, bias=bias)
247
+
248
+ if not self.only_cross_attention:
249
+ # only relevant for the `AddedKVProcessor` classes
250
+ self.to_k = nn.Linear(self.cross_attention_dim, self.inner_kv_dim, bias=bias)
251
+ self.to_v = nn.Linear(self.cross_attention_dim, self.inner_kv_dim, bias=bias)
252
+ else:
253
+ self.to_k = None
254
+ self.to_v = None
255
+
256
+ self.added_proj_bias = added_proj_bias
257
+ if self.added_kv_proj_dim is not None:
258
+ self.add_k_proj = nn.Linear(added_kv_proj_dim, self.inner_kv_dim, bias=added_proj_bias)
259
+ self.add_v_proj = nn.Linear(added_kv_proj_dim, self.inner_kv_dim, bias=added_proj_bias)
260
+ if self.context_pre_only is not None:
261
+ self.add_q_proj = nn.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias)
262
+ else:
263
+ self.add_q_proj = None
264
+ self.add_k_proj = None
265
+ self.add_v_proj = None
266
+
267
+ if not self.pre_only:
268
+ self.to_out = nn.ModuleList([])
269
+ self.to_out.append(nn.Linear(self.inner_dim, self.out_dim, bias=out_bias))
270
+ self.to_out.append(nn.Dropout(dropout))
271
+ else:
272
+ self.to_out = None
273
+
274
+ if self.context_pre_only is not None and not self.context_pre_only:
275
+ self.to_add_out = nn.Linear(self.inner_dim, self.out_context_dim, bias=out_bias)
276
+ else:
277
+ self.to_add_out = None
278
+
279
+ if qk_norm is not None and added_kv_proj_dim is not None:
280
+ if qk_norm == "layer_norm":
281
+ self.norm_added_q = nn.LayerNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
282
+ self.norm_added_k = nn.LayerNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
283
+ elif qk_norm == "fp32_layer_norm":
284
+ self.norm_added_q = FP32LayerNorm(dim_head, elementwise_affine=False, bias=False, eps=eps)
285
+ self.norm_added_k = FP32LayerNorm(dim_head, elementwise_affine=False, bias=False, eps=eps)
286
+ elif qk_norm == "rms_norm":
287
+ self.norm_added_q = RMSNorm(dim_head, eps=eps)
288
+ self.norm_added_k = RMSNorm(dim_head, eps=eps)
289
+ elif qk_norm == "rms_norm_across_heads":
290
+ # Wan applies qk norm across all heads
291
+ # Wan also doesn't apply a q norm
292
+ self.norm_added_q = None
293
+ self.norm_added_k = RMSNorm(dim_head * kv_heads, eps=eps)
294
+ else:
295
+ raise ValueError(
296
+ f"unknown qk_norm: {qk_norm}. Should be one of `None,'layer_norm','fp32_layer_norm','rms_norm'`"
297
+ )
298
+ else:
299
+ self.norm_added_q = None
300
+ self.norm_added_k = None
301
+
302
+ # set attention processor
303
+ # We use the AttnProcessor2_0 by default when torch 2.x is used which uses
304
+ # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
305
+ # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
306
+ if processor is None:
307
+ processor = (
308
+ AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") and self.scale_qk else AttnProcessor()
309
+ )
310
+ self.set_processor(processor)
311
+
312
+ # def set_use_xla_flash_attention(
313
+ # self,
314
+ # use_xla_flash_attention: bool,
315
+ # partition_spec: Optional[Tuple[Optional[str], ...]] = None,
316
+ # is_flux=False,
317
+ # ) -> None:
318
+ # r"""
319
+ # Set whether to use xla flash attention from `torch_xla` or not.
320
+
321
+ # Args:
322
+ # use_xla_flash_attention (`bool`):
323
+ # Whether to use pallas flash attention kernel from `torch_xla` or not.
324
+ # partition_spec (`Tuple[]`, *optional*):
325
+ # Specify the partition specification if using SPMD. Otherwise None.
326
+ # """
327
+ # if use_xla_flash_attention:
328
+ # if not is_torch_xla_available:
329
+ # raise "torch_xla is not available"
330
+ # elif is_torch_xla_version("<", "2.3"):
331
+ # raise "flash attention pallas kernel is supported from torch_xla version 2.3"
332
+ # elif is_spmd() and is_torch_xla_version("<", "2.4"):
333
+ # raise "flash attention pallas kernel using SPMD is supported from torch_xla version 2.4"
334
+ # else:
335
+ # if is_flux:
336
+ # processor = XLAFluxFlashAttnProcessor2_0(partition_spec)
337
+ # else:
338
+ # processor = XLAFlashAttnProcessor2_0(partition_spec)
339
+ # else:
340
+ # processor = (
341
+ # AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") and self.scale_qk else AttnProcessor()
342
+ # )
343
+ # self.set_processor(processor)
344
+
345
+ # def set_use_npu_flash_attention(self, use_npu_flash_attention: bool) -> None:
346
+ # r"""
347
+ # Set whether to use npu flash attention from `torch_npu` or not.
348
+
349
+ # """
350
+ # if use_npu_flash_attention:
351
+ # processor = AttnProcessorNPU()
352
+ # else:
353
+ # # set attention processor
354
+ # # We use the AttnProcessor2_0 by default when torch 2.x is used which uses
355
+ # # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
356
+ # # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
357
+ # processor = (
358
+ # AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") and self.scale_qk else AttnProcessor()
359
+ # )
360
+ # self.set_processor(processor)
361
+
362
+ # def set_use_memory_efficient_attention_xformers(
363
+ # self, use_memory_efficient_attention_xformers: bool, attention_op: Optional[Callable] = None
364
+ # ) -> None:
365
+ # r"""
366
+ # Set whether to use memory efficient attention from `xformers` or not.
367
+
368
+ # Args:
369
+ # use_memory_efficient_attention_xformers (`bool`):
370
+ # Whether to use memory efficient attention from `xformers` or not.
371
+ # attention_op (`Callable`, *optional*):
372
+ # The attention operation to use. Defaults to `None` which uses the default attention operation from
373
+ # `xformers`.
374
+ # """
375
+ # is_custom_diffusion = hasattr(self, "processor") and isinstance(
376
+ # self.processor,
377
+ # (CustomDiffusionAttnProcessor, CustomDiffusionXFormersAttnProcessor, CustomDiffusionAttnProcessor2_0),
378
+ # )
379
+ # is_added_kv_processor = hasattr(self, "processor") and isinstance(
380
+ # self.processor,
381
+ # (
382
+ # AttnAddedKVProcessor,
383
+ # AttnAddedKVProcessor2_0,
384
+ # SlicedAttnAddedKVProcessor,
385
+ # XFormersAttnAddedKVProcessor,
386
+ # ),
387
+ # )
388
+ # is_ip_adapter = hasattr(self, "processor") and isinstance(
389
+ # self.processor,
390
+ # (IPAdapterAttnProcessor, IPAdapterAttnProcessor2_0, IPAdapterXFormersAttnProcessor),
391
+ # )
392
+ # is_joint_processor = hasattr(self, "processor") and isinstance(
393
+ # self.processor,
394
+ # (
395
+ # JointAttnProcessor2_0,
396
+ # XFormersJointAttnProcessor,
397
+ # ),
398
+ # )
399
+
400
+ # if use_memory_efficient_attention_xformers:
401
+ # if is_added_kv_processor and is_custom_diffusion:
402
+ # raise NotImplementedError(
403
+ # f"Memory efficient attention is currently not supported for custom diffusion for attention processor type {self.processor}"
404
+ # )
405
+ # if not is_xformers_available():
406
+ # raise ModuleNotFoundError(
407
+ # (
408
+ # "Refer to https://github.com/facebookresearch/xformers for more information on how to install"
409
+ # " xformers"
410
+ # ),
411
+ # name="xformers",
412
+ # )
413
+ # elif not torch.cuda.is_available():
414
+ # raise ValueError(
415
+ # "torch.cuda.is_available() should be True but is False. xformers' memory efficient attention is"
416
+ # " only available for GPU "
417
+ # )
418
+ # else:
419
+ # try:
420
+ # # Make sure we can run the memory efficient attention
421
+ # dtype = None
422
+ # if attention_op is not None:
423
+ # op_fw, op_bw = attention_op
424
+ # dtype, *_ = op_fw.SUPPORTED_DTYPES
425
+ # q = torch.randn((1, 2, 40), device="cuda", dtype=dtype)
426
+ # _ = xformers.ops.memory_efficient_attention(q, q, q)
427
+ # except Exception as e:
428
+ # raise e
429
+
430
+ # if is_custom_diffusion:
431
+ # processor = CustomDiffusionXFormersAttnProcessor(
432
+ # train_kv=self.processor.train_kv,
433
+ # train_q_out=self.processor.train_q_out,
434
+ # hidden_size=self.processor.hidden_size,
435
+ # cross_attention_dim=self.processor.cross_attention_dim,
436
+ # attention_op=attention_op,
437
+ # )
438
+ # processor.load_state_dict(self.processor.state_dict())
439
+ # if hasattr(self.processor, "to_k_custom_diffusion"):
440
+ # processor.to(self.processor.to_k_custom_diffusion.weight.device)
441
+ # elif is_added_kv_processor:
442
+ # # TODO(Patrick, Suraj, William) - currently xformers doesn't work for UnCLIP
443
+ # # which uses this type of cross attention ONLY because the attention mask of format
444
+ # # [0, ..., -10.000, ..., 0, ...,] is not supported
445
+ # # throw warning
446
+ # logger.info(
447
+ # "Memory efficient attention with `xformers` might currently not work correctly if an attention mask is required for the attention operation."
448
+ # )
449
+ # processor = XFormersAttnAddedKVProcessor(attention_op=attention_op)
450
+ # elif is_ip_adapter:
451
+ # processor = IPAdapterXFormersAttnProcessor(
452
+ # hidden_size=self.processor.hidden_size,
453
+ # cross_attention_dim=self.processor.cross_attention_dim,
454
+ # num_tokens=self.processor.num_tokens,
455
+ # scale=self.processor.scale,
456
+ # attention_op=attention_op,
457
+ # )
458
+ # processor.load_state_dict(self.processor.state_dict())
459
+ # if hasattr(self.processor, "to_k_ip"):
460
+ # processor.to(
461
+ # device=self.processor.to_k_ip[0].weight.device, dtype=self.processor.to_k_ip[0].weight.dtype
462
+ # )
463
+ # elif is_joint_processor:
464
+ # processor = XFormersJointAttnProcessor(attention_op=attention_op)
465
+ # else:
466
+ # processor = XFormersAttnProcessor(attention_op=attention_op)
467
+ # else:
468
+ # if is_custom_diffusion:
469
+ # attn_processor_class = (
470
+ # CustomDiffusionAttnProcessor2_0
471
+ # if hasattr(F, "scaled_dot_product_attention")
472
+ # else CustomDiffusionAttnProcessor
473
+ # )
474
+ # processor = attn_processor_class(
475
+ # train_kv=self.processor.train_kv,
476
+ # train_q_out=self.processor.train_q_out,
477
+ # hidden_size=self.processor.hidden_size,
478
+ # cross_attention_dim=self.processor.cross_attention_dim,
479
+ # )
480
+ # processor.load_state_dict(self.processor.state_dict())
481
+ # if hasattr(self.processor, "to_k_custom_diffusion"):
482
+ # processor.to(self.processor.to_k_custom_diffusion.weight.device)
483
+ # elif is_ip_adapter:
484
+ # processor = IPAdapterAttnProcessor2_0(
485
+ # hidden_size=self.processor.hidden_size,
486
+ # cross_attention_dim=self.processor.cross_attention_dim,
487
+ # num_tokens=self.processor.num_tokens,
488
+ # scale=self.processor.scale,
489
+ # )
490
+ # processor.load_state_dict(self.processor.state_dict())
491
+ # if hasattr(self.processor, "to_k_ip"):
492
+ # processor.to(
493
+ # device=self.processor.to_k_ip[0].weight.device, dtype=self.processor.to_k_ip[0].weight.dtype
494
+ # )
495
+ # else:
496
+ # # set attention processor
497
+ # # We use the AttnProcessor2_0 by default when torch 2.x is used which uses
498
+ # # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
499
+ # # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
500
+ # processor = (
501
+ # AttnProcessor2_0()
502
+ # if hasattr(F, "scaled_dot_product_attention") and self.scale_qk
503
+ # else AttnProcessor()
504
+ # )
505
+
506
+ # self.set_processor(processor)
507
+
508
+ # def set_attention_slice(self, slice_size: int) -> None:
509
+ # r"""
510
+ # Set the slice size for attention computation.
511
+
512
+ # Args:
513
+ # slice_size (`int`):
514
+ # The slice size for attention computation.
515
+ # """
516
+ # if slice_size is not None and slice_size > self.sliceable_head_dim:
517
+ # raise ValueError(f"slice_size {slice_size} has to be smaller or equal to {self.sliceable_head_dim}.")
518
+
519
+ # if slice_size is not None and self.added_kv_proj_dim is not None:
520
+ # processor = SlicedAttnAddedKVProcessor(slice_size)
521
+ # elif slice_size is not None:
522
+ # processor = SlicedAttnProcessor(slice_size)
523
+ # elif self.added_kv_proj_dim is not None:
524
+ # processor = AttnAddedKVProcessor()
525
+ # else:
526
+ # # set attention processor
527
+ # # We use the AttnProcessor2_0 by default when torch 2.x is used which uses
528
+ # # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
529
+ # # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
530
+ # processor = (
531
+ # AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") and self.scale_qk else AttnProcessor()
532
+ # )
533
+
534
+ # self.set_processor(processor)
535
+
536
+ def set_processor(self, processor: "AttnProcessor") -> None:
537
+ r"""
538
+ Set the attention processor to use.
539
+
540
+ Args:
541
+ processor (`AttnProcessor`):
542
+ The attention processor to use.
543
+ """
544
+ # if current processor is in `self._modules` and if passed `processor` is not, we need to
545
+ # pop `processor` from `self._modules`
546
+ if (
547
+ hasattr(self, "processor")
548
+ and isinstance(self.processor, torch.nn.Module)
549
+ and not isinstance(processor, torch.nn.Module)
550
+ ):
551
+ logger.info(f"You are removing possibly trained weights of {self.processor} with {processor}")
552
+ self._modules.pop("processor")
553
+
554
+ self.processor = processor
555
+
556
+ def get_processor(self, return_deprecated_lora: bool = False) -> "AttentionProcessor":
557
+ r"""
558
+ Get the attention processor in use.
559
+
560
+ Args:
561
+ return_deprecated_lora (`bool`, *optional*, defaults to `False`):
562
+ Set to `True` to return the deprecated LoRA attention processor.
563
+
564
+ Returns:
565
+ "AttentionProcessor": The attention processor in use.
566
+ """
567
+ if not return_deprecated_lora:
568
+ return self.processor
569
+
570
+ def forward(
571
+ self,
572
+ hidden_states: torch.Tensor,
573
+ encoder_hidden_states: Optional[torch.Tensor] = None,
574
+ map_aware_mask: Optional[torch.FloatTensor] = None,
575
+ **cross_attention_kwargs,
576
+ ) -> torch.Tensor:
577
+ r"""
578
+ The forward method of the `Attention` class.
579
+
580
+ Args:
581
+ hidden_states (`torch.Tensor`):
582
+ The hidden states of the query.
583
+ encoder_hidden_states (`torch.Tensor`, *optional*):
584
+ The hidden states of the encoder.
585
+ map_aware_mask (`torch.Tensor`, *optional*):
586
+ The attention mask to use. If `None`, no mask is applied.
587
+ **cross_attention_kwargs:
588
+ Additional keyword arguments to pass along to the cross attention.
589
+
590
+ Returns:
591
+ `torch.Tensor`: The output of the attention layer.
592
+ """
593
+ # The `Attention` class can call different attention processors / attention functions
594
+ # here we simply pass along all tensors to the selected processor class
595
+ # For standard processors that are defined here, `**cross_attention_kwargs` is empty
596
+
597
+ attn_parameters = set(inspect.signature(self.processor.__call__).parameters.keys())
598
+ quiet_attn_parameters = {"ip_adapter_masks", "ip_hidden_states"}
599
+ unused_kwargs = [
600
+ k for k, _ in cross_attention_kwargs.items() if k not in attn_parameters and k not in quiet_attn_parameters
601
+ ]
602
+ if len(unused_kwargs) > 0:
603
+ logger.warning(
604
+ f"cross_attention_kwargs {unused_kwargs} are not expected by {self.processor.__class__.__name__} and will be ignored."
605
+ )
606
+ cross_attention_kwargs = {k: w for k, w in cross_attention_kwargs.items() if k in attn_parameters}
607
+
608
+ return self.processor(
609
+ self,
610
+ hidden_states,
611
+ encoder_hidden_states=encoder_hidden_states,
612
+ attention_mask=map_aware_mask,
613
+ **cross_attention_kwargs,
614
+ )
615
+
616
+ def batch_to_head_dim(self, tensor: torch.Tensor) -> torch.Tensor:
617
+ r"""
618
+ Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size // heads, seq_len, dim * heads]`. `heads`
619
+ is the number of heads initialized while constructing the `Attention` class.
620
+
621
+ Args:
622
+ tensor (`torch.Tensor`): The tensor to reshape.
623
+
624
+ Returns:
625
+ `torch.Tensor`: The reshaped tensor.
626
+ """
627
+ head_size = self.heads
628
+ batch_size, seq_len, dim = tensor.shape
629
+ tensor = tensor.reshape(batch_size // head_size, head_size, seq_len, dim)
630
+ tensor = tensor.permute(0, 2, 1, 3).reshape(batch_size // head_size, seq_len, dim * head_size)
631
+ return tensor
632
+
633
+ def head_to_batch_dim(self, tensor: torch.Tensor, out_dim: int = 3) -> torch.Tensor:
634
+ r"""
635
+ Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size, seq_len, heads, dim // heads]` `heads` is
636
+ the number of heads initialized while constructing the `Attention` class.
637
+
638
+ Args:
639
+ tensor (`torch.Tensor`): The tensor to reshape.
640
+ out_dim (`int`, *optional*, defaults to `3`): The output dimension of the tensor. If `3`, the tensor is
641
+ reshaped to `[batch_size * heads, seq_len, dim // heads]`.
642
+
643
+ Returns:
644
+ `torch.Tensor`: The reshaped tensor.
645
+ """
646
+ head_size = self.heads
647
+ if tensor.ndim == 3:
648
+ batch_size, seq_len, dim = tensor.shape
649
+ extra_dim = 1
650
+ else:
651
+ batch_size, extra_dim, seq_len, dim = tensor.shape
652
+ tensor = tensor.reshape(batch_size, seq_len * extra_dim, head_size, dim // head_size)
653
+ tensor = tensor.permute(0, 2, 1, 3)
654
+
655
+ if out_dim == 3:
656
+ tensor = tensor.reshape(batch_size * head_size, seq_len * extra_dim, dim // head_size)
657
+
658
+ return tensor
659
+
660
+ def get_attention_scores(
661
+ self, query: torch.Tensor, key: torch.Tensor, attention_mask: Optional[torch.Tensor] = None
662
+ ) -> torch.Tensor:
663
+ r"""
664
+ Compute the attention scores.
665
+
666
+ Args:
667
+ query (`torch.Tensor`): The query tensor.
668
+ key (`torch.Tensor`): The key tensor.
669
+ attention_mask (`torch.Tensor`, *optional*): The attention mask to use. If `None`, no mask is applied.
670
+
671
+ Returns:
672
+ `torch.Tensor`: The attention probabilities/scores.
673
+ """
674
+ dtype = query.dtype
675
+ if self.upcast_attention:
676
+ query = query.float()
677
+ key = key.float()
678
+
679
+ if attention_mask is None:
680
+ baddbmm_input = torch.empty(
681
+ query.shape[0], query.shape[1], key.shape[1], dtype=query.dtype, device=query.device
682
+ )
683
+ beta = 0
684
+ else:
685
+ baddbmm_input = attention_mask
686
+ beta = 1
687
+
688
+ attention_scores = torch.baddbmm(
689
+ baddbmm_input,
690
+ query,
691
+ key.transpose(-1, -2),
692
+ beta=beta,
693
+ alpha=self.scale,
694
+ )
695
+ del baddbmm_input
696
+
697
+ if self.upcast_softmax:
698
+ attention_scores = attention_scores.float()
699
+
700
+ attention_probs = attention_scores.softmax(dim=-1)
701
+ del attention_scores
702
+
703
+ attention_probs = attention_probs.to(dtype)
704
+
705
+ return attention_probs
706
+
707
+ def prepare_attention_mask(
708
+ self, attention_mask: torch.Tensor, target_length: int, batch_size: int, out_dim: int = 3
709
+ ) -> torch.Tensor:
710
+ r"""
711
+ Prepare the attention mask for the attention computation.
712
+
713
+ Args:
714
+ attention_mask (`torch.Tensor`):
715
+ The attention mask to prepare.
716
+ target_length (`int`):
717
+ The target length of the attention mask. This is the length of the attention mask after padding.
718
+ batch_size (`int`):
719
+ The batch size, which is used to repeat the attention mask.
720
+ out_dim (`int`, *optional*, defaults to `3`):
721
+ The output dimension of the attention mask. Can be either `3` or `4`.
722
+
723
+ Returns:
724
+ `torch.Tensor`: The prepared attention mask.
725
+ """
726
+ head_size = self.heads
727
+ if attention_mask is None:
728
+ return attention_mask
729
+
730
+ current_length: int = attention_mask.shape[-1]
731
+ if current_length != target_length:
732
+ if attention_mask.device.type == "mps":
733
+ # HACK: MPS: Does not support padding by greater than dimension of input tensor.
734
+ # Instead, we can manually construct the padding tensor.
735
+ padding_shape = (attention_mask.shape[0], attention_mask.shape[1], target_length)
736
+ padding = torch.zeros(padding_shape, dtype=attention_mask.dtype, device=attention_mask.device)
737
+ attention_mask = torch.cat([attention_mask, padding], dim=2)
738
+ else:
739
+ # TODO: for pipelines such as stable-diffusion, padding cross-attn mask:
740
+ # we want to instead pad by (0, remaining_length), where remaining_length is:
741
+ # remaining_length: int = target_length - current_length
742
+ # TODO: re-enable tests/models/test_models_unet_2d_condition.py#test_model_xattn_padding
743
+ attention_mask = F.pad(attention_mask, (0, target_length), value=0.0)
744
+
745
+ if out_dim == 3:
746
+ if attention_mask.shape[0] < batch_size * head_size:
747
+ attention_mask = attention_mask.repeat_interleave(
748
+ head_size, dim=0, output_size=attention_mask.shape[0] * head_size
749
+ )
750
+ elif out_dim == 4:
751
+ attention_mask = attention_mask.unsqueeze(1)
752
+ attention_mask = attention_mask.repeat_interleave(
753
+ head_size, dim=1, output_size=attention_mask.shape[1] * head_size
754
+ )
755
+
756
+ return attention_mask
757
+
758
+ def norm_encoder_hidden_states(self, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
759
+ r"""
760
+ Normalize the encoder hidden states. Requires `self.norm_cross` to be specified when constructing the
761
+ `Attention` class.
762
+
763
+ Args:
764
+ encoder_hidden_states (`torch.Tensor`): Hidden states of the encoder.
765
+
766
+ Returns:
767
+ `torch.Tensor`: The normalized encoder hidden states.
768
+ """
769
+ assert self.norm_cross is not None, "self.norm_cross must be defined to call self.norm_encoder_hidden_states"
770
+
771
+ if isinstance(self.norm_cross, nn.LayerNorm):
772
+ encoder_hidden_states = self.norm_cross(encoder_hidden_states)
773
+ elif isinstance(self.norm_cross, nn.GroupNorm):
774
+ # Group norm norms along the channels dimension and expects
775
+ # input to be in the shape of (N, C, *). In this case, we want
776
+ # to norm along the hidden dimension, so we need to move
777
+ # (batch_size, sequence_length, hidden_size) ->
778
+ # (batch_size, hidden_size, sequence_length)
779
+ encoder_hidden_states = encoder_hidden_states.transpose(1, 2)
780
+ encoder_hidden_states = self.norm_cross(encoder_hidden_states)
781
+ encoder_hidden_states = encoder_hidden_states.transpose(1, 2)
782
+ else:
783
+ assert False
784
+
785
+ return encoder_hidden_states
786
+
787
+ @torch.no_grad()
788
+ def fuse_projections(self, fuse=True):
789
+ device = self.to_q.weight.data.device
790
+ dtype = self.to_q.weight.data.dtype
791
+
792
+ if not self.is_cross_attention:
793
+ # fetch weight matrices.
794
+ concatenated_weights = torch.cat([self.to_q.weight.data, self.to_k.weight.data, self.to_v.weight.data])
795
+ in_features = concatenated_weights.shape[1]
796
+ out_features = concatenated_weights.shape[0]
797
+
798
+ # create a new single projection layer and copy over the weights.
799
+ self.to_qkv = nn.Linear(in_features, out_features, bias=self.use_bias, device=device, dtype=dtype)
800
+ self.to_qkv.weight.copy_(concatenated_weights)
801
+ if self.use_bias:
802
+ concatenated_bias = torch.cat([self.to_q.bias.data, self.to_k.bias.data, self.to_v.bias.data])
803
+ self.to_qkv.bias.copy_(concatenated_bias)
804
+
805
+ else:
806
+ concatenated_weights = torch.cat([self.to_k.weight.data, self.to_v.weight.data])
807
+ in_features = concatenated_weights.shape[1]
808
+ out_features = concatenated_weights.shape[0]
809
+
810
+ self.to_kv = nn.Linear(in_features, out_features, bias=self.use_bias, device=device, dtype=dtype)
811
+ self.to_kv.weight.copy_(concatenated_weights)
812
+ if self.use_bias:
813
+ concatenated_bias = torch.cat([self.to_k.bias.data, self.to_v.bias.data])
814
+ self.to_kv.bias.copy_(concatenated_bias)
815
+
816
+ # handle added projections for SD3 and others.
817
+ if (
818
+ getattr(self, "add_q_proj", None) is not None
819
+ and getattr(self, "add_k_proj", None) is not None
820
+ and getattr(self, "add_v_proj", None) is not None
821
+ ):
822
+ concatenated_weights = torch.cat(
823
+ [self.add_q_proj.weight.data, self.add_k_proj.weight.data, self.add_v_proj.weight.data]
824
+ )
825
+ in_features = concatenated_weights.shape[1]
826
+ out_features = concatenated_weights.shape[0]
827
+
828
+ self.to_added_qkv = nn.Linear(
829
+ in_features, out_features, bias=self.added_proj_bias, device=device, dtype=dtype
830
+ )
831
+ self.to_added_qkv.weight.copy_(concatenated_weights)
832
+ if self.added_proj_bias:
833
+ concatenated_bias = torch.cat(
834
+ [self.add_q_proj.bias.data, self.add_k_proj.bias.data, self.add_v_proj.bias.data]
835
+ )
836
+ self.to_added_qkv.bias.copy_(concatenated_bias)
837
+
838
+ self.fused_projections = fuse
839
+
840
+ class MapAwareAttnProcessor2_0:
841
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
842
+
843
+ def __init__(self):
844
+ if not hasattr(F, "scaled_dot_product_attention"):
845
+ raise ImportError("JointAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
846
+
847
+ def __call__(
848
+ self,
849
+ attn: Attention,
850
+ hidden_states: torch.FloatTensor,
851
+ encoder_hidden_states: torch.FloatTensor = None,
852
+ attention_mask: Optional[torch.FloatTensor] = None,
853
+ *args,
854
+ **kwargs,
855
+ ) -> torch.FloatTensor:
856
+ # print("attention_mask: ", attention_mask)
857
+ residual = hidden_states
858
+
859
+ batch_size = hidden_states.shape[0]
860
+
861
+ # `sample` projections.
862
+ query = attn.to_q(hidden_states)
863
+ key = attn.to_k(hidden_states)
864
+ value = attn.to_v(hidden_states)
865
+
866
+ inner_dim = key.shape[-1]
867
+ head_dim = inner_dim // attn.heads
868
+
869
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
870
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
871
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
872
+
873
+ if attn.norm_q is not None:
874
+ query = attn.norm_q(query)
875
+ if attn.norm_k is not None:
876
+ key = attn.norm_k(key)
877
+
878
+ # `context` projections.
879
+ if encoder_hidden_states is not None:
880
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
881
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
882
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
883
+
884
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
885
+ batch_size, -1, attn.heads, head_dim
886
+ ).transpose(1, 2)
887
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
888
+ batch_size, -1, attn.heads, head_dim
889
+ ).transpose(1, 2)
890
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
891
+ batch_size, -1, attn.heads, head_dim
892
+ ).transpose(1, 2)
893
+
894
+ if attn.norm_added_q is not None:
895
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
896
+ if attn.norm_added_k is not None:
897
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
898
+
899
+ # print(f"image q: {query.shape}, image k: {key.shape}, image v: {value.shape}") # [B, 24, 1024, 64]
900
+ # print(f"text q: {encoder_hidden_states_query_proj.shape}, text k: {encoder_hidden_states_key_proj.shape}, text v: {encoder_hidden_states_value_proj.shape}")
901
+ # [B, 24, 154, 64]
902
+
903
+ query = torch.cat([query, encoder_hidden_states_query_proj], dim=2)
904
+ key = torch.cat([key, encoder_hidden_states_key_proj], dim=2)
905
+ value = torch.cat([value, encoder_hidden_states_value_proj], dim=2)
906
+
907
+ # print(f"Joint - query shape: {query.shape}, key shape: {key.shape}, value shape: {value.shape}")
908
+ # [B, 24, 1178, 64]
909
+ map_aware_mask = attention_mask
910
+ else:
911
+ map_aware_mask = None
912
+ # print(
913
+ # "map_aware_mask:",
914
+ # None if map_aware_mask is None else (map_aware_mask.shape, map_aware_mask.dtype)
915
+ # )
916
+
917
+ # print("query: ", query.shape, query.dtype)
918
+ if map_aware_mask is not None:
919
+ map_aware_mask = map_aware_mask.to(query.dtype)
920
+
921
+
922
+ hidden_states = F.scaled_dot_product_attention(query, key, value,
923
+ attn_mask=map_aware_mask,
924
+ dropout_p=0.0,
925
+ is_causal=False)
926
+
927
+
928
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
929
+ hidden_states = hidden_states.to(query.dtype)
930
+
931
+ if encoder_hidden_states is not None:
932
+ # Split the attention outputs.
933
+ hidden_states, encoder_hidden_states = (
934
+ hidden_states[:, : residual.shape[1]],
935
+ hidden_states[:, residual.shape[1] :],
936
+ )
937
+ if not attn.context_pre_only:
938
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
939
+
940
+ # linear proj
941
+ hidden_states = attn.to_out[0](hidden_states)
942
+ # dropout
943
+ hidden_states = attn.to_out[1](hidden_states)
944
+
945
+ if encoder_hidden_states is not None:
946
+ return hidden_states, encoder_hidden_states
947
+ else:
948
+ return hidden_states
949
+
950
+ class MapAwareTransformerBlock(nn.Module):
951
+ r"""
952
+ A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
953
+
954
+ Reference: https://huggingface.co/papers/2403.03206
955
+
956
+ Parameters:
957
+ dim (`int`): The number of channels in the input and output.
958
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
959
+ attention_head_dim (`int`): The number of channels in each head.
960
+ context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
961
+ processing of `context` conditions.
962
+ """
963
+
964
+ def __init__(
965
+ self,
966
+ dim: int,
967
+ num_attention_heads: int,
968
+ attention_head_dim: int,
969
+ context_pre_only: bool = False,
970
+ qk_norm: Optional[str] = None,
971
+ use_dual_attention: bool = False,
972
+ ):
973
+ super().__init__()
974
+
975
+ self.use_dual_attention = use_dual_attention
976
+ self.context_pre_only = context_pre_only
977
+ context_norm_type = "ada_norm_continous" if context_pre_only else "ada_norm_zero"
978
+
979
+ if use_dual_attention:
980
+ self.norm1 = SD35AdaLayerNormZeroX(dim)
981
+ else:
982
+ self.norm1 = AdaLayerNormZero(dim)
983
+
984
+ if context_norm_type == "ada_norm_continous":
985
+ self.norm1_context = AdaLayerNormContinuous(
986
+ dim, dim, elementwise_affine=False, eps=1e-6, bias=True, norm_type="layer_norm"
987
+ )
988
+ elif context_norm_type == "ada_norm_zero":
989
+ self.norm1_context = AdaLayerNormZero(dim)
990
+ else:
991
+ raise ValueError(
992
+ f"Unknown context_norm_type: {context_norm_type}, currently only support `ada_norm_continous`, `ada_norm_zero`"
993
+ )
994
+
995
+ # if hasattr(F, "scaled_dot_product_attention"):
996
+ # processor = JointAttnProcessor2_0()
997
+ # else:
998
+ # raise ValueError(
999
+ # "The current PyTorch version does not support the `scaled_dot_product_attention` function."
1000
+ # )
1001
+
1002
+ self.attn = MapAwareAttention(
1003
+ query_dim=dim,
1004
+ cross_attention_dim=None,
1005
+ added_kv_proj_dim=dim,
1006
+ dim_head=attention_head_dim,
1007
+ heads=num_attention_heads,
1008
+ out_dim=dim,
1009
+ context_pre_only=context_pre_only,
1010
+ bias=True,
1011
+ processor=MapAwareAttnProcessor2_0(),
1012
+ qk_norm=qk_norm,
1013
+ eps=1e-6,
1014
+ )
1015
+
1016
+ if use_dual_attention:
1017
+ self.attn2 = Attention(
1018
+ query_dim=dim,
1019
+ cross_attention_dim=None,
1020
+ dim_head=attention_head_dim,
1021
+ heads=num_attention_heads,
1022
+ out_dim=dim,
1023
+ bias=True,
1024
+ processor=JointAttnProcessor2_0(),
1025
+ qk_norm=qk_norm,
1026
+ eps=1e-6,
1027
+ )
1028
+ else:
1029
+ self.attn2 = None
1030
+
1031
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
1032
+ self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
1033
+
1034
+ if not context_pre_only:
1035
+ self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
1036
+ self.ff_context = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
1037
+ else:
1038
+ self.norm2_context = None
1039
+ self.ff_context = None
1040
+
1041
+ # let chunk size default to None
1042
+ self._chunk_size = None
1043
+ self._chunk_dim = 0
1044
+
1045
+ # Copied from diffusers.models.attention.BasicTransformerBlock.set_chunk_feed_forward
1046
+ def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
1047
+ # Sets chunk feed-forward
1048
+ self._chunk_size = chunk_size
1049
+ self._chunk_dim = dim
1050
+
1051
+ def forward(
1052
+ self,
1053
+ hidden_states: torch.FloatTensor,
1054
+ encoder_hidden_states: torch.FloatTensor,
1055
+ temb: torch.FloatTensor,
1056
+ map_aware_mask: Optional[torch.FloatTensor] = None,
1057
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
1058
+ ):
1059
+ joint_attention_kwargs = joint_attention_kwargs or {}
1060
+ if self.use_dual_attention:
1061
+ # print(f"hidden_states: {type(hidden_states)}")
1062
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp, norm_hidden_states2, gate_msa2 = self.norm1(
1063
+ hidden_states, emb=temb
1064
+ )
1065
+ else:
1066
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
1067
+
1068
+ if self.context_pre_only:
1069
+ norm_encoder_hidden_states = self.norm1_context(encoder_hidden_states, temb)
1070
+ else:
1071
+ norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
1072
+ encoder_hidden_states, emb=temb
1073
+ )
1074
+
1075
+ # Attention.
1076
+ attn_output, context_attn_output = self.attn(
1077
+ hidden_states=norm_hidden_states,
1078
+ encoder_hidden_states=norm_encoder_hidden_states,
1079
+ map_aware_mask=map_aware_mask,
1080
+ **joint_attention_kwargs,
1081
+ )
1082
+
1083
+ # Process attention outputs for the `hidden_states`.
1084
+ attn_output = gate_msa.unsqueeze(1) * attn_output
1085
+ hidden_states = hidden_states + attn_output
1086
+
1087
+ if self.use_dual_attention:
1088
+ attn_output2 = self.attn2(hidden_states=norm_hidden_states2, **joint_attention_kwargs)
1089
+ attn_output2 = gate_msa2.unsqueeze(1) * attn_output2
1090
+ hidden_states = hidden_states + attn_output2
1091
+
1092
+ norm_hidden_states = self.norm2(hidden_states)
1093
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
1094
+ if self._chunk_size is not None:
1095
+ # "feed_forward_chunk_size" can be used to save memory
1096
+ ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size)
1097
+ else:
1098
+ ff_output = self.ff(norm_hidden_states)
1099
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
1100
+
1101
+ hidden_states = hidden_states + ff_output
1102
+
1103
+ # Process attention outputs for the `encoder_hidden_states`.
1104
+ if self.context_pre_only:
1105
+ encoder_hidden_states = None
1106
+ else:
1107
+ context_attn_output = c_gate_msa.unsqueeze(1) * context_attn_output
1108
+ encoder_hidden_states = encoder_hidden_states + context_attn_output
1109
+
1110
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
1111
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
1112
+ if self._chunk_size is not None:
1113
+ # "feed_forward_chunk_size" can be used to save memory
1114
+ context_ff_output = _chunked_feed_forward(
1115
+ self.ff_context, norm_encoder_hidden_states, self._chunk_dim, self._chunk_size
1116
+ )
1117
+ else:
1118
+ context_ff_output = self.ff_context(norm_encoder_hidden_states)
1119
+ encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
1120
+
1121
+ return encoder_hidden_states, hidden_states
1122
+
1123
+ @maybe_allow_in_graph
1124
+ class SD3SingleTransformerBlock(nn.Module):
1125
+ def __init__(
1126
+ self,
1127
+ dim: int,
1128
+ num_attention_heads: int,
1129
+ attention_head_dim: int,
1130
+ ):
1131
+ super().__init__()
1132
+
1133
+ self.norm1 = AdaLayerNormZero(dim)
1134
+ self.attn = Attention(
1135
+ query_dim=dim,
1136
+ dim_head=attention_head_dim,
1137
+ heads=num_attention_heads,
1138
+ out_dim=dim,
1139
+ bias=True,
1140
+ processor=JointAttnProcessor2_0(),
1141
+ eps=1e-6,
1142
+ )
1143
+
1144
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
1145
+ self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
1146
+
1147
+ def forward(self, hidden_states: torch.Tensor, temb: torch.Tensor):
1148
+ # 1. Attention
1149
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
1150
+ attn_output = self.attn(hidden_states=norm_hidden_states, encoder_hidden_states=None)
1151
+ attn_output = gate_msa.unsqueeze(1) * attn_output
1152
+ hidden_states = hidden_states + attn_output
1153
+
1154
+ # 2. Feed Forward
1155
+ norm_hidden_states = self.norm2(hidden_states)
1156
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp.unsqueeze(1)) + shift_mlp.unsqueeze(1)
1157
+ ff_output = self.ff(norm_hidden_states)
1158
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
1159
+ hidden_states = hidden_states + ff_output
1160
+
1161
+ return hidden_states
1162
+
1163
+
1164
+ class IntrinsicWeatherSD3Transformer2DModel(
1165
+ ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin, SD3Transformer2DLoadersMixin
1166
+ ):
1167
+ """
1168
+ The Transformer model introduced in [Stable Diffusion 3](https://huggingface.co/papers/2403.03206).
1169
+
1170
+ Parameters:
1171
+ sample_size (`int`, defaults to `128`):
1172
+ The width/height of the latents. This is fixed during training since it is used to learn a number of
1173
+ position embeddings.
1174
+ patch_size (`int`, defaults to `2`):
1175
+ Patch size to turn the input data into small patches.
1176
+ in_channels (`int`, defaults to `16`):
1177
+ The number of latent channels in the input.
1178
+ num_layers (`int`, defaults to `18`):
1179
+ The number of layers of transformer blocks to use.
1180
+ attention_head_dim (`int`, defaults to `64`):
1181
+ The number of channels in each head.
1182
+ num_attention_heads (`int`, defaults to `18`):
1183
+ The number of heads to use for multi-head attention.
1184
+ joint_attention_dim (`int`, defaults to `4096`):
1185
+ The embedding dimension to use for joint text-image attention.
1186
+ caption_projection_dim (`int`, defaults to `1152`):
1187
+ The embedding dimension of caption embeddings.
1188
+ pooled_projection_dim (`int`, defaults to `2048`):
1189
+ The embedding dimension of pooled text projections.
1190
+ out_channels (`int`, defaults to `16`):
1191
+ The number of latent channels in the output.
1192
+ pos_embed_max_size (`int`, defaults to `96`):
1193
+ The maximum latent height/width of positional embeddings.
1194
+ dual_attention_layers (`Tuple[int, ...]`, defaults to `()`):
1195
+ The number of dual-stream transformer blocks to use.
1196
+ qk_norm (`str`, *optional*, defaults to `None`):
1197
+ The normalization to use for query and key in the attention layer. If `None`, no normalization is used.
1198
+ """
1199
+
1200
+ _supports_gradient_checkpointing = True
1201
+ _no_split_modules = ["JointTransformerBlock"]
1202
+ _skip_layerwise_casting_patterns = ["pos_embed", "norm"]
1203
+
1204
+ @register_to_config
1205
+ def __init__(
1206
+ self,
1207
+ sample_size: int = 128,
1208
+ patch_size: int = 2,
1209
+ in_channels: int = 16,
1210
+ num_layers: int = 18,
1211
+ attention_head_dim: int = 64,
1212
+ num_attention_heads: int = 18,
1213
+ joint_attention_dim: int = 4096,
1214
+ caption_projection_dim: int = 1152,
1215
+ pooled_projection_dim: int = 2048,
1216
+ out_channels: int = 16,
1217
+ pos_embed_max_size: int = 96,
1218
+ dual_attention_layers: Tuple[
1219
+ int, ...
1220
+ ] = (), # () for sd3.0; (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) for sd3.5
1221
+ qk_norm: Optional[str] = None,
1222
+ ):
1223
+ super().__init__()
1224
+ self.out_channels = out_channels if out_channels is not None else in_channels
1225
+ self.inner_dim = num_attention_heads * attention_head_dim
1226
+
1227
+ self.pos_embed = PatchEmbed(
1228
+ height=sample_size,
1229
+ width=sample_size,
1230
+ patch_size=patch_size,
1231
+ in_channels=in_channels,
1232
+ embed_dim=self.inner_dim,
1233
+ pos_embed_max_size=pos_embed_max_size, # hard-code for now.
1234
+ )
1235
+ self.time_text_embed = CombinedTimestepTextProjEmbeddings(
1236
+ embedding_dim=self.inner_dim, pooled_projection_dim=pooled_projection_dim
1237
+ )
1238
+ self.context_embedder = nn.Linear(joint_attention_dim, caption_projection_dim)
1239
+
1240
+ self.transformer_blocks = nn.ModuleList(
1241
+ [
1242
+ MapAwareTransformerBlock(
1243
+ dim=self.inner_dim,
1244
+ num_attention_heads=num_attention_heads,
1245
+ attention_head_dim=attention_head_dim,
1246
+ context_pre_only=i == num_layers - 1,
1247
+ qk_norm=qk_norm,
1248
+ use_dual_attention=True if i in dual_attention_layers else False,
1249
+ )
1250
+ for i in range(num_layers)
1251
+ ]
1252
+ )
1253
+
1254
+ self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
1255
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
1256
+
1257
+ self.gradient_checkpointing = False
1258
+
1259
+ # Copied from diffusers.models.unets.unet_3d_condition.UNet3DConditionModel.enable_forward_chunking
1260
+ def enable_forward_chunking(self, chunk_size: Optional[int] = None, dim: int = 0) -> None:
1261
+ """
1262
+ Sets the attention processor to use [feed forward
1263
+ chunking](https://huggingface.co/blog/reformer#2-chunked-feed-forward-layers).
1264
+
1265
+ Parameters:
1266
+ chunk_size (`int`, *optional*):
1267
+ The chunk size of the feed-forward layers. If not specified, will run feed-forward layer individually
1268
+ over each tensor of dim=`dim`.
1269
+ dim (`int`, *optional*, defaults to `0`):
1270
+ The dimension over which the feed-forward computation should be chunked. Choose between dim=0 (batch)
1271
+ or dim=1 (sequence length).
1272
+ """
1273
+ if dim not in [0, 1]:
1274
+ raise ValueError(f"Make sure to set `dim` to either 0 or 1, not {dim}")
1275
+
1276
+ # By default chunk size is 1
1277
+ chunk_size = chunk_size or 1
1278
+
1279
+ def fn_recursive_feed_forward(module: torch.nn.Module, chunk_size: int, dim: int):
1280
+ if hasattr(module, "set_chunk_feed_forward"):
1281
+ module.set_chunk_feed_forward(chunk_size=chunk_size, dim=dim)
1282
+
1283
+ for child in module.children():
1284
+ fn_recursive_feed_forward(child, chunk_size, dim)
1285
+
1286
+ for module in self.children():
1287
+ fn_recursive_feed_forward(module, chunk_size, dim)
1288
+
1289
+ # Copied from diffusers.models.unets.unet_3d_condition.UNet3DConditionModel.disable_forward_chunking
1290
+ def disable_forward_chunking(self):
1291
+ def fn_recursive_feed_forward(module: torch.nn.Module, chunk_size: int, dim: int):
1292
+ if hasattr(module, "set_chunk_feed_forward"):
1293
+ module.set_chunk_feed_forward(chunk_size=chunk_size, dim=dim)
1294
+
1295
+ for child in module.children():
1296
+ fn_recursive_feed_forward(child, chunk_size, dim)
1297
+
1298
+ for module in self.children():
1299
+ fn_recursive_feed_forward(module, None, 0)
1300
+
1301
+ @property
1302
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
1303
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
1304
+ r"""
1305
+ Returns:
1306
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
1307
+ indexed by its weight name.
1308
+ """
1309
+ # set recursively
1310
+ processors = {}
1311
+
1312
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
1313
+ if hasattr(module, "get_processor"):
1314
+ processors[f"{name}.processor"] = module.get_processor()
1315
+
1316
+ for sub_name, child in module.named_children():
1317
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
1318
+
1319
+ return processors
1320
+
1321
+ for name, module in self.named_children():
1322
+ fn_recursive_add_processors(name, module, processors)
1323
+
1324
+ return processors
1325
+
1326
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
1327
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
1328
+ r"""
1329
+ Sets the attention processor to use to compute attention.
1330
+
1331
+ Parameters:
1332
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
1333
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
1334
+ for **all** `Attention` layers.
1335
+
1336
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
1337
+ processor. This is strongly recommended when setting trainable attention processors.
1338
+
1339
+ """
1340
+ count = len(self.attn_processors.keys())
1341
+
1342
+ if isinstance(processor, dict) and len(processor) != count:
1343
+ raise ValueError(
1344
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
1345
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
1346
+ )
1347
+
1348
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
1349
+ if hasattr(module, "set_processor"):
1350
+ if not isinstance(processor, dict):
1351
+ module.set_processor(processor)
1352
+ else:
1353
+ module.set_processor(processor.pop(f"{name}.processor"))
1354
+
1355
+ for sub_name, child in module.named_children():
1356
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
1357
+
1358
+ for name, module in self.named_children():
1359
+ fn_recursive_attn_processor(name, module, processor)
1360
+
1361
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedJointAttnProcessor2_0
1362
+ def fuse_qkv_projections(self):
1363
+ """
1364
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
1365
+ are fused. For cross-attention modules, key and value projection matrices are fused.
1366
+
1367
+ <Tip warning={true}>
1368
+
1369
+ This API is 🧪 experimental.
1370
+
1371
+ </Tip>
1372
+ """
1373
+ self.original_attn_processors = None
1374
+
1375
+ for _, attn_processor in self.attn_processors.items():
1376
+ if "Added" in str(attn_processor.__class__.__name__):
1377
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
1378
+
1379
+ self.original_attn_processors = self.attn_processors
1380
+
1381
+ for module in self.modules():
1382
+ if isinstance(module, Attention):
1383
+ module.fuse_projections(fuse=True)
1384
+
1385
+ self.set_attn_processor(FusedJointAttnProcessor2_0())
1386
+
1387
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
1388
+ def unfuse_qkv_projections(self):
1389
+ """Disables the fused QKV projection if enabled.
1390
+
1391
+ <Tip warning={true}>
1392
+
1393
+ This API is 🧪 experimental.
1394
+
1395
+ </Tip>
1396
+
1397
+ """
1398
+ if self.original_attn_processors is not None:
1399
+ self.set_attn_processor(self.original_attn_processors)
1400
+
1401
+ def forward(
1402
+ self,
1403
+ hidden_states: torch.Tensor,
1404
+ encoder_hidden_states: torch.Tensor = None,
1405
+ pooled_projections: torch.Tensor = None,
1406
+ timestep: torch.LongTensor = None,
1407
+ block_controlnet_hidden_states: List = None,
1408
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
1409
+ return_dict: bool = True,
1410
+ skip_layers: Optional[List[int]] = None,
1411
+ map_aware_mask: Optional[torch.FloatTensor] = None,
1412
+ ) -> Union[torch.Tensor, Transformer2DModelOutput]:
1413
+ """
1414
+ The [`SD3Transformer2DModel`] forward method.
1415
+
1416
+ Args:
1417
+ hidden_states (`torch.Tensor` of shape `(batch size, channel, height, width)`):
1418
+ Input `hidden_states`.
1419
+ encoder_hidden_states (`torch.Tensor` of shape `(batch size, sequence_len, embed_dims)`):
1420
+ Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
1421
+ pooled_projections (`torch.Tensor` of shape `(batch_size, projection_dim)`):
1422
+ Embeddings projected from the embeddings of input conditions.
1423
+ timestep (`torch.LongTensor`):
1424
+ Used to indicate denoising step.
1425
+ block_controlnet_hidden_states (`list` of `torch.Tensor`):
1426
+ A list of tensors that if specified are added to the residuals of transformer blocks.
1427
+ joint_attention_kwargs (`dict`, *optional*):
1428
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1429
+ `self.processor` in
1430
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1431
+ return_dict (`bool`, *optional*, defaults to `True`):
1432
+ Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
1433
+ tuple.
1434
+ skip_layers (`list` of `int`, *optional*):
1435
+ A list of layer indices to skip during the forward pass.
1436
+
1437
+ Returns:
1438
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
1439
+ `tuple` where the first element is the sample tensor.
1440
+ """
1441
+ if joint_attention_kwargs is not None:
1442
+ joint_attention_kwargs = joint_attention_kwargs.copy()
1443
+ lora_scale = joint_attention_kwargs.pop("scale", 1.0)
1444
+ else:
1445
+ lora_scale = 1.0
1446
+
1447
+ if USE_PEFT_BACKEND:
1448
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
1449
+ scale_lora_layers(self, lora_scale)
1450
+ else:
1451
+ if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
1452
+ logger.warning(
1453
+ "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
1454
+ )
1455
+
1456
+ height, width = hidden_states.shape[-2:]
1457
+
1458
+ hidden_states = self.pos_embed(hidden_states) # takes care of adding positional embeddings too.
1459
+ temb = self.time_text_embed(timestep, pooled_projections)
1460
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
1461
+
1462
+ if joint_attention_kwargs is not None and "ip_adapter_image_embeds" in joint_attention_kwargs:
1463
+ ip_adapter_image_embeds = joint_attention_kwargs.pop("ip_adapter_image_embeds")
1464
+ ip_hidden_states, ip_temb = self.image_proj(ip_adapter_image_embeds, timestep)
1465
+
1466
+ joint_attention_kwargs.update(ip_hidden_states=ip_hidden_states, temb=ip_temb)
1467
+
1468
+ for index_block, block in enumerate(self.transformer_blocks):
1469
+ # print("index: ", index_block)
1470
+
1471
+ # Skip specified layers
1472
+ is_skip = True if skip_layers is not None and index_block in skip_layers else False
1473
+
1474
+ if index_block >= (self.config.num_layers // 2) and map_aware_mask is not None:
1475
+ current_mask = map_aware_mask.to(hidden_states.device)
1476
+ else:
1477
+ current_mask = None
1478
+
1479
+ # print("transformer: map_aware_mask:", current_mask.shape if current_mask is not None else None)
1480
+
1481
+ if torch.is_grad_enabled() and self.gradient_checkpointing and not is_skip:
1482
+ encoder_hidden_states, hidden_states = self._gradient_checkpointing_func(
1483
+ block,
1484
+ hidden_states,
1485
+ encoder_hidden_states,
1486
+ temb,
1487
+ current_mask,
1488
+ joint_attention_kwargs,
1489
+ )
1490
+ elif not is_skip:
1491
+ encoder_hidden_states, hidden_states = block(
1492
+ hidden_states=hidden_states,
1493
+ encoder_hidden_states=encoder_hidden_states,
1494
+ temb=temb,
1495
+ map_aware_mask=current_mask,
1496
+ joint_attention_kwargs=joint_attention_kwargs,
1497
+ )
1498
+
1499
+ # controlnet residual
1500
+ if block_controlnet_hidden_states is not None and block.context_pre_only is False:
1501
+ interval_control = len(self.transformer_blocks) / len(block_controlnet_hidden_states)
1502
+ hidden_states = hidden_states + block_controlnet_hidden_states[int(index_block / interval_control)]
1503
+
1504
+ hidden_states = self.norm_out(hidden_states, temb)
1505
+ hidden_states = self.proj_out(hidden_states)
1506
+
1507
+ # unpatchify
1508
+ patch_size = self.config.patch_size
1509
+ height = height // patch_size
1510
+ width = width // patch_size
1511
+
1512
+ hidden_states = hidden_states.reshape(
1513
+ shape=(hidden_states.shape[0], height, width, patch_size, patch_size, self.out_channels)
1514
+ )
1515
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
1516
+ output = hidden_states.reshape(
1517
+ shape=(hidden_states.shape[0], self.out_channels, height * patch_size, width * patch_size)
1518
+ )
1519
+
1520
+ if USE_PEFT_BACKEND:
1521
+ # remove `lora_scale` from each PEFT layer
1522
+ unscale_lora_layers(self, lora_scale)
1523
+
1524
+ if not return_dict:
1525
+ return (output,)
1526
+
1527
+ return Transformer2DModelOutput(sample=output)