SunderAli17 commited on
Commit
2560b63
1 Parent(s): 489a5bc

Create attention.py

Browse files
Files changed (1) hide show
  1. module/attention.py +257 -0
module/attention.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copy from diffusers.models.attention.py
2
+
3
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ from typing import Any, Dict, Optional
17
+
18
+ import torch
19
+ import torch.nn.functional as F
20
+ from torch import nn
21
+
22
+ from diffusers.utils import deprecate, logging
23
+ from diffusers.utils.torch_utils import maybe_allow_in_graph
24
+ from diffusers.models.activations import GEGLU, GELU, ApproximateGELU
25
+ from diffusers.models.attention_processor import Attention
26
+ from diffusers.models.embeddings import SinusoidalPositionalEmbedding
27
+ from diffusers.models.normalization import AdaLayerNorm, AdaLayerNormContinuous, AdaLayerNormZero, RMSNorm
28
+
29
+ from module.min_sdxl import LoRACompatibleLinear, LoRALinearLayer
30
+
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+ def create_custom_forward(module):
35
+ def custom_forward(*inputs):
36
+ return module(*inputs)
37
+
38
+ return custom_forward
39
+
40
+ def maybe_grad_checkpoint(resnet, attn, hidden_states, temb, encoder_hidden_states, adapter_hidden_states, do_ckpt=True):
41
+
42
+ if do_ckpt:
43
+ hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb)
44
+ hidden_states, extracted_kv = torch.utils.checkpoint.checkpoint(
45
+ create_custom_forward(attn), hidden_states, encoder_hidden_states, adapter_hidden_states, use_reentrant=False
46
+ )
47
+ else:
48
+ hidden_states = resnet(hidden_states, temb)
49
+ hidden_states, extracted_kv = attn(
50
+ hidden_states,
51
+ encoder_hidden_states=encoder_hidden_states,
52
+ adapter_hidden_states=adapter_hidden_states,
53
+ )
54
+ return hidden_states, extracted_kv
55
+
56
+
57
+ def init_lora_in_attn(attn_module, rank: int = 4, is_kvcopy=False):
58
+ # Set the `lora_layer` attribute of the attention-related matrices.
59
+
60
+ attn_module.to_k.set_lora_layer(
61
+ LoRALinearLayer(
62
+ in_features=attn_module.to_k.in_features, out_features=attn_module.to_k.out_features, rank=rank
63
+ )
64
+ )
65
+ attn_module.to_v.set_lora_layer(
66
+ LoRALinearLayer(
67
+ in_features=attn_module.to_v.in_features, out_features=attn_module.to_v.out_features, rank=rank
68
+ )
69
+ )
70
+
71
+ if not is_kvcopy:
72
+ attn_module.to_q.set_lora_layer(
73
+ LoRALinearLayer(
74
+ in_features=attn_module.to_q.in_features, out_features=attn_module.to_q.out_features, rank=rank
75
+ )
76
+ )
77
+
78
+ attn_module.to_out[0].set_lora_layer(
79
+ LoRALinearLayer(
80
+ in_features=attn_module.to_out[0].in_features,
81
+ out_features=attn_module.to_out[0].out_features,
82
+ rank=rank,
83
+ )
84
+ )
85
+
86
+ def drop_kvs(encoder_kvs, drop_chance):
87
+ for layer in encoder_kvs:
88
+ len_tokens = encoder_kvs[layer].self_attention.k.shape[1]
89
+ idx_to_keep = (torch.rand(len_tokens) > drop_chance)
90
+
91
+ encoder_kvs[layer].self_attention.k = encoder_kvs[layer].self_attention.k[:, idx_to_keep]
92
+ encoder_kvs[layer].self_attention.v = encoder_kvs[layer].self_attention.v[:, idx_to_keep]
93
+
94
+ return encoder_kvs
95
+
96
+ def clone_kvs(encoder_kvs):
97
+ cloned_kvs = {}
98
+ for layer in encoder_kvs:
99
+ sa_cpy = KVCache(k=encoder_kvs[layer].self_attention.k.clone(),
100
+ v=encoder_kvs[layer].self_attention.v.clone())
101
+
102
+ ca_cpy = KVCache(k=encoder_kvs[layer].cross_attention.k.clone(),
103
+ v=encoder_kvs[layer].cross_attention.v.clone())
104
+
105
+ cloned_layer_cache = AttentionCache(self_attention=sa_cpy, cross_attention=ca_cpy)
106
+
107
+ cloned_kvs[layer] = cloned_layer_cache
108
+
109
+ return cloned_kvs
110
+
111
+
112
+ class KVCache(object):
113
+ def __init__(self, k, v):
114
+ self.k = k
115
+ self.v = v
116
+
117
+ class AttentionCache(object):
118
+ def __init__(self, self_attention: KVCache, cross_attention: KVCache):
119
+ self.self_attention = self_attention
120
+ self.cross_attention = cross_attention
121
+
122
+ class KVCopy(nn.Module):
123
+ def __init__(
124
+ self, inner_dim, cross_attention_dim=None,
125
+ ):
126
+ super(KVCopy, self).__init__()
127
+
128
+ in_dim = cross_attention_dim or inner_dim
129
+
130
+ self.to_k = LoRACompatibleLinear(in_dim, inner_dim, bias=False)
131
+ self.to_v = LoRACompatibleLinear(in_dim, inner_dim, bias=False)
132
+
133
+ def forward(self, hidden_states):
134
+
135
+ k = self.to_k(hidden_states)
136
+ v = self.to_v(hidden_states)
137
+
138
+ return KVCache(k=k, v=v)
139
+
140
+ def init_kv_copy(self, source_attn):
141
+ with torch.no_grad():
142
+ self.to_k.weight.copy_(source_attn.to_k.weight)
143
+ self.to_v.weight.copy_(source_attn.to_v.weight)
144
+
145
+
146
+ class FeedForward(nn.Module):
147
+ r"""
148
+ A feed-forward layer.
149
+ Parameters:
150
+ dim (`int`): The number of channels in the input.
151
+ dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
152
+ mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
153
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
154
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
155
+ final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
156
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
157
+ """
158
+
159
+ def __init__(
160
+ self,
161
+ dim: int,
162
+ dim_out: Optional[int] = None,
163
+ mult: int = 4,
164
+ dropout: float = 0.0,
165
+ activation_fn: str = "geglu",
166
+ final_dropout: bool = False,
167
+ inner_dim=None,
168
+ bias: bool = True,
169
+ ):
170
+ super().__init__()
171
+ if inner_dim is None:
172
+ inner_dim = int(dim * mult)
173
+ dim_out = dim_out if dim_out is not None else dim
174
+
175
+ if activation_fn == "gelu":
176
+ act_fn = GELU(dim, inner_dim, bias=bias)
177
+ if activation_fn == "gelu-approximate":
178
+ act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
179
+ elif activation_fn == "geglu":
180
+ act_fn = GEGLU(dim, inner_dim, bias=bias)
181
+ elif activation_fn == "geglu-approximate":
182
+ act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
183
+
184
+ self.net = nn.ModuleList([])
185
+ # project in
186
+ self.net.append(act_fn)
187
+ # project dropout
188
+ self.net.append(nn.Dropout(dropout))
189
+ # project out
190
+ self.net.append(nn.Linear(inner_dim, dim_out, bias=bias))
191
+ # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
192
+ if final_dropout:
193
+ self.net.append(nn.Dropout(dropout))
194
+
195
+ def forward(self, hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
196
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
197
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
198
+ deprecate("scale", "1.0.0", deprecation_message)
199
+ for module in self.net:
200
+ hidden_states = module(hidden_states)
201
+ return hidden_states
202
+
203
+
204
+ def _chunked_feed_forward(ff: nn.Module, hidden_states: torch.Tensor, chunk_dim: int, chunk_size: int):
205
+ # "feed_forward_chunk_size" can be used to save memory
206
+ if hidden_states.shape[chunk_dim] % chunk_size != 0:
207
+ raise ValueError(
208
+ f"`hidden_states` dimension to be chunked: {hidden_states.shape[chunk_dim]} has to be divisible by chunk size: {chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."
209
+ )
210
+
211
+ num_chunks = hidden_states.shape[chunk_dim] // chunk_size
212
+ ff_output = torch.cat(
213
+ [ff(hid_slice) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)],
214
+ dim=chunk_dim,
215
+ )
216
+ return ff_output
217
+
218
+
219
+ @maybe_allow_in_graph
220
+ class GatedSelfAttentionDense(nn.Module):
221
+ r"""
222
+ A gated self-attention dense layer that combines visual features and object features.
223
+ Parameters:
224
+ query_dim (`int`): The number of channels in the query.
225
+ context_dim (`int`): The number of channels in the context.
226
+ n_heads (`int`): The number of heads to use for attention.
227
+ d_head (`int`): The number of channels in each head.
228
+ """
229
+
230
+ def __init__(self, query_dim: int, context_dim: int, n_heads: int, d_head: int):
231
+ super().__init__()
232
+
233
+ # we need a linear projection since we need cat visual feature and obj feature
234
+ self.linear = nn.Linear(context_dim, query_dim)
235
+
236
+ self.attn = Attention(query_dim=query_dim, heads=n_heads, dim_head=d_head)
237
+ self.ff = FeedForward(query_dim, activation_fn="geglu")
238
+
239
+ self.norm1 = nn.LayerNorm(query_dim)
240
+ self.norm2 = nn.LayerNorm(query_dim)
241
+
242
+ self.register_parameter("alpha_attn", nn.Parameter(torch.tensor(0.0)))
243
+ self.register_parameter("alpha_dense", nn.Parameter(torch.tensor(0.0)))
244
+
245
+ self.enabled = True
246
+
247
+ def forward(self, x: torch.Tensor, objs: torch.Tensor) -> torch.Tensor:
248
+ if not self.enabled:
249
+ return x
250
+
251
+ n_visual = x.shape[1]
252
+ objs = self.linear(objs)
253
+
254
+ x = x + self.alpha_attn.tanh() * self.attn(self.norm1(torch.cat([x, objs], dim=1)))[:, :n_visual, :]
255
+ x = x + self.alpha_dense.tanh() * self.ff(self.norm2(x))
256
+
257
+ return x