cyd0806 commited on
Commit
66bfb92
·
verified ·
1 Parent(s): ccb84ca

Upload src/SubjectGeniusTransformerBlock.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. src/SubjectGeniusTransformerBlock.py +296 -0
src/SubjectGeniusTransformerBlock.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ipdb
2
+ import torch
3
+ from typing import List, Optional, Dict, Any
4
+ from torch import FloatTensor, Tensor
5
+ from diffusers.models.attention_processor import Attention, F
6
+ from .lora_switching_module import enable_lora,module_active_adapters
7
+ from diffusers.models.embeddings import apply_rotary_emb
8
+
9
+ def attn_forward(
10
+ attn: Attention,
11
+ hidden_states: torch.FloatTensor,
12
+ condition_types: List[str],
13
+ encoder_hidden_states: torch.FloatTensor = None,
14
+ condition_latents: torch.FloatTensor = None,
15
+ attention_mask: Optional[torch.FloatTensor] = None,
16
+ image_rotary_emb: Optional[torch.Tensor] = None,
17
+ cond_rotary_embs: Optional[List[torch.Tensor]] = None,
18
+ model_config: Optional[Dict[str, Any]] = {},
19
+ ) -> tuple[Any, Any, list[FloatTensor] | None] | tuple[Any, Any] | tuple[Tensor, Tensor] | Tensor:
20
+ batch_size, seq_len, _ = hidden_states.shape
21
+ # base_key / base_value: [text,noise] if encoder_hidden_states is not None else [noise]
22
+ with enable_lora([attn.to_q, attn.to_k, attn.to_v], [item for item in module_active_adapters(attn.to_q) if item not in condition_types]):
23
+ base_key = attn.to_k(hidden_states)
24
+ base_value = attn.to_v(hidden_states)
25
+ query = attn.to_q(hidden_states)
26
+
27
+ inner_dim = query.shape[-1]
28
+ head_dim = inner_dim // attn.heads
29
+
30
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
31
+ base_key = base_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
32
+ base_value = base_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
33
+
34
+ if attn.norm_q is not None:
35
+ query = attn.norm_q(query)
36
+ if attn.norm_k is not None:
37
+ base_key = attn.norm_k(base_key)
38
+
39
+ # the attention in FluxSingleTransformerBlock does not use `encoder_hidden_states`
40
+ if encoder_hidden_states is not None:
41
+ # `context` projections.
42
+ seq_len = seq_len + encoder_hidden_states.shape[1]
43
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
44
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
45
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
46
+
47
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
48
+ batch_size, -1, attn.heads, head_dim
49
+ ).transpose(1, 2)
50
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
51
+ batch_size, -1, attn.heads, head_dim
52
+ ).transpose(1, 2)
53
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
54
+ batch_size, -1, attn.heads, head_dim
55
+ ).transpose(1, 2)
56
+
57
+ if attn.norm_added_q is not None:
58
+ encoder_hidden_states_query_proj = attn.norm_added_q(
59
+ encoder_hidden_states_query_proj
60
+ )
61
+ if attn.norm_added_k is not None:
62
+ encoder_hidden_states_key_proj = attn.norm_added_k(
63
+ encoder_hidden_states_key_proj
64
+ )
65
+
66
+ # concat the text embedding and noise embedding
67
+ query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
68
+ base_key = torch.cat([encoder_hidden_states_key_proj, base_key], dim=2)
69
+ base_value = torch.cat([encoder_hidden_states_value_proj, base_value], dim=2)
70
+
71
+ if image_rotary_emb is not None:
72
+ query = apply_rotary_emb(query, image_rotary_emb)
73
+ base_key = apply_rotary_emb(base_key, image_rotary_emb)
74
+
75
+ condition_latents_output_list = []
76
+
77
+ key = base_key
78
+ value = base_value
79
+ if condition_latents is not None and len(condition_latents) > 0:
80
+ for i, cond_type in enumerate(condition_types):
81
+ with enable_lora([attn.to_q,attn.to_k, attn.to_v], [cond_type]):
82
+ cond_query = attn.to_q(condition_latents[i])
83
+ cond_key = attn.to_k(condition_latents[i])
84
+ cond_value = attn.to_v(condition_latents[i])
85
+ cond_query = cond_query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
86
+ cond_key = cond_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
87
+ cond_value = cond_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
88
+
89
+ if attn.norm_q is not None:
90
+ cond_query = attn.norm_q(cond_query)
91
+ if attn.norm_k is not None:
92
+ cond_key = attn.norm_k(cond_key)
93
+
94
+ if cond_rotary_embs is not None:
95
+ cond_query = apply_rotary_emb(cond_query, cond_rotary_embs[i])
96
+ cond_key = apply_rotary_emb(cond_key, cond_rotary_embs[i])
97
+
98
+ key = torch.cat([key, cond_key], dim=2)
99
+ value = torch.cat([value, cond_value], dim=2)
100
+ mix_cond_key = torch.cat([base_key, cond_key], dim=2)
101
+ mix_cond_value = torch.cat([base_value, cond_value], dim=2)
102
+
103
+ condition_latents_output = F.scaled_dot_product_attention(
104
+ cond_query, mix_cond_key, mix_cond_value, dropout_p=0.0, is_causal=False, attn_mask=attention_mask
105
+ )
106
+ condition_latents_output = condition_latents_output.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
107
+ condition_latents_output_list.append(condition_latents_output)
108
+
109
+ hidden_states = F.scaled_dot_product_attention(
110
+ query, key, value, dropout_p=0.0, is_causal=False, attn_mask=attention_mask
111
+ )
112
+ hidden_states = hidden_states.transpose(1, 2).reshape(
113
+ batch_size, -1, attn.heads * head_dim
114
+ )
115
+
116
+ if encoder_hidden_states is not None:
117
+ encoder_hidden_states, hidden_states = (
118
+ hidden_states[:, : encoder_hidden_states.shape[1]],
119
+ hidden_states[:, encoder_hidden_states.shape[1] :],
120
+ )
121
+ with enable_lora([attn.to_out[0]], [item for item in module_active_adapters(attn.to_out[0]) if item not in condition_types]):
122
+ # linear proj
123
+ hidden_states = attn.to_out[0](hidden_states)
124
+ # dropout
125
+ hidden_states = attn.to_out[1](hidden_states)
126
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
127
+
128
+ if condition_latents is not None and len(condition_latents) > 0:
129
+ for i, cond_type in enumerate(condition_types):
130
+ with enable_lora([attn.to_out[0]], [cond_type]):
131
+ condition_latents_output_list[i] = attn.to_out[0](condition_latents_output_list[i])
132
+ condition_latents_output_list[i] = attn.to_out[1](condition_latents_output_list[i])
133
+ return hidden_states, encoder_hidden_states, condition_latents_output_list
134
+
135
+ else:
136
+ return hidden_states, condition_latents_output_list
137
+
138
+
139
+
140
+ def block_forward(
141
+ self,
142
+ hidden_states: torch.Tensor,
143
+ encoder_hidden_states: torch.Tensor,
144
+ condition_latents: List[torch.Tensor] = None,
145
+ temb: torch.Tensor = None,
146
+ cond_temb: List[torch.Tensor] = None,
147
+ cond_rotary_embs=None,
148
+ image_rotary_emb=None,
149
+ condition_types: List[str]=None,
150
+ model_config: Optional[Dict[str, Any]] = {},
151
+ ):
152
+ use_cond = condition_latents is not None and len(condition_latents) > 0
153
+ # norm : hidden_states->norm_hidden_states, encoder_hidden_states->norm_encoder_hidden_states, condition_latents->norm_condition_latent_list
154
+ with enable_lora([self.norm1.linear], [item for item in module_active_adapters(self.norm1.linear) if item not in condition_types]):
155
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
156
+ hidden_states, emb=temb
157
+ )
158
+ norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = (
159
+ self.norm1_context(encoder_hidden_states, emb=temb)
160
+ )
161
+ norm_condition_latent_list = []
162
+ cond_gate_msa_list = []
163
+ cond_shift_mlp_list = []
164
+ cond_scale_mlp_list = []
165
+ cond_gate_mlp_list = []
166
+ if use_cond:
167
+ for i, cond_type in enumerate(condition_types):
168
+ with enable_lora([self.norm1.linear],[cond_type]):
169
+ norm_condition_latent,cond_gate_msa,cond_shift_mlp,cond_scale_mlp,cond_gate_mlp,= self.norm1(
170
+ condition_latents[i], emb=cond_temb
171
+ )
172
+ norm_condition_latent_list.append(norm_condition_latent)
173
+ cond_gate_msa_list.append(cond_gate_msa)
174
+ cond_shift_mlp_list.append(cond_shift_mlp)
175
+ cond_scale_mlp_list.append(cond_scale_mlp)
176
+ cond_gate_mlp_list.append(cond_gate_mlp)
177
+
178
+ # Attention. attn_output, context_attn_output, cond_attn_output_list
179
+ attn_output, context_attn_output,cond_attn_output_list = attn_forward(
180
+ self.attn,
181
+ model_config=model_config,
182
+ hidden_states=norm_hidden_states,
183
+ condition_types=condition_types,
184
+ encoder_hidden_states=norm_encoder_hidden_states,
185
+ condition_latents=norm_condition_latent_list if use_cond else None,
186
+ image_rotary_emb=image_rotary_emb,
187
+ cond_rotary_embs=cond_rotary_embs if use_cond else None,
188
+ )
189
+ # Process attention outputs. Gate + Resnet. hidden_states, encoder_hidden_states, condition_latents
190
+ # 1. hidden_states
191
+ attn_output = gate_msa.unsqueeze(1) * attn_output
192
+ hidden_states = hidden_states + attn_output
193
+ # 2. encoder_hidden_states
194
+ context_attn_output = c_gate_msa.unsqueeze(1) * context_attn_output
195
+ encoder_hidden_states = encoder_hidden_states + context_attn_output
196
+ # 3. condition_latents
197
+ if use_cond:
198
+ for i, cond_type in enumerate(condition_types):
199
+ cond_attn_output_list[i] = cond_gate_msa_list[i].unsqueeze(1) * cond_attn_output_list[i]
200
+ condition_latents[i] = condition_latents[i] + cond_attn_output_list[i]
201
+ if model_config.get("add_cond_attn", False):
202
+ hidden_states += cond_attn_output_list[i]
203
+
204
+ # LayerNorm + Scaling + Shift.
205
+ # hidden_states->norm_hidden_states, encoder_hidden_states->norm_encoder_hidden_states, condition_latents->norm_condition_latent_list
206
+ # 1. hidden_states
207
+ norm_hidden_states = self.norm2(hidden_states)
208
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
209
+
210
+ # 2. encoder_hidden_states
211
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
212
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
213
+
214
+ # 3. condition_latents
215
+ if use_cond:
216
+ for i, cond_type in enumerate(condition_types):
217
+ norm_condition_latent_list[i] = self.norm2(condition_latents[i])
218
+ norm_condition_latent_list[i] = norm_condition_latent_list[i] * (1 + cond_scale_mlp_list[i][:, None]) + cond_shift_mlp_list[i][:, None]
219
+
220
+ # MLP Feed-forward + Gate
221
+ # 1. hidden_states
222
+ with enable_lora([self.ff.net[2]], [item for item in module_active_adapters(self.ff.net[2]) if item not in condition_types]):
223
+ hidden_states = hidden_states + gate_mlp.unsqueeze(1) * self.ff(norm_hidden_states)
224
+ # 2. encoder_hidden_states
225
+ encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * self.ff_context(norm_encoder_hidden_states)
226
+ # 3. condition_latents
227
+ if use_cond:
228
+ for i, cond_type in enumerate(condition_types):
229
+ with enable_lora([self.ff.net[2]], [cond_type]):
230
+ condition_latents[i] = condition_latents[i] + cond_gate_mlp_list[i].unsqueeze(1) * self.ff(norm_condition_latent_list[i])
231
+
232
+ # Clip to avoid overflow.
233
+ if encoder_hidden_states.dtype == torch.float16:
234
+ encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
235
+
236
+ return encoder_hidden_states, hidden_states, condition_latents if use_cond else None
237
+
238
+
239
+ def single_block_forward(
240
+ self,
241
+ hidden_states: torch.Tensor,
242
+ condition_latents: List[torch.Tensor] = None,
243
+ temb: torch.Tensor = None,
244
+ cond_temb: List[torch.Tensor] = None,
245
+ image_rotary_emb=None,
246
+ cond_rotary_embs=None,
247
+ condition_types: List[str] = None,
248
+ model_config: Optional[Dict[str, Any]] = {},
249
+ ):
250
+ using_cond = condition_latents is not None and len(condition_latents) > 0
251
+ with enable_lora([self.norm.linear,self.proj_mlp],[item for item in module_active_adapters(self.norm.linear) if item not in condition_types]):
252
+ norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
253
+ mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
254
+
255
+ norm_condition_latent_list = []
256
+ mlp_condition_latent_list = []
257
+ cond_gate_list = []
258
+
259
+ if using_cond:
260
+ for i, cond_type in enumerate(condition_types):
261
+ with enable_lora([self.norm.linear, self.proj_mlp],[cond_type]):
262
+ norm_condition_latents, cond_gate = self.norm(condition_latents[i], emb=cond_temb)
263
+ mlp_condition_latents = self.act_mlp(self.proj_mlp(norm_condition_latents))
264
+ norm_condition_latent_list.append(norm_condition_latents)
265
+ mlp_condition_latent_list.append(mlp_condition_latents)
266
+ cond_gate_list.append(cond_gate)
267
+
268
+ attn_output, cond_attn_output = attn_forward(
269
+ self.attn,
270
+ model_config=model_config,
271
+ hidden_states=norm_hidden_states,
272
+ condition_types= condition_types,
273
+ image_rotary_emb=image_rotary_emb,
274
+ **(
275
+ {
276
+ "condition_latents": norm_condition_latent_list,
277
+ "cond_rotary_embs": cond_rotary_embs if using_cond else None,
278
+ }
279
+ if using_cond
280
+ else {}
281
+ ),
282
+ )
283
+ with enable_lora([self.proj_out], [item for item in module_active_adapters(self.proj_out) if item not in condition_types]):
284
+ hidden_states = hidden_states + gate.unsqueeze(1) * self.proj_out(torch.cat([attn_output, mlp_hidden_states], dim=2))
285
+ if using_cond:
286
+ for i, cond_type in enumerate(condition_types):
287
+ with enable_lora([self.proj_out],[cond_type]):
288
+ attn_mlp_condition_latents = torch.cat([cond_attn_output[i], mlp_condition_latent_list[i]], dim=2)
289
+ attn_mlp_condition_latents = cond_gate_list[i].unsqueeze(1) * self.proj_out(attn_mlp_condition_latents)
290
+ condition_latents[i] = condition_latents[i] + attn_mlp_condition_latents
291
+
292
+ if hidden_states.dtype == torch.float16:
293
+ hidden_states = hidden_states.clip(-65504, 65504)
294
+
295
+ return (hidden_states,None) if not using_cond else (hidden_states, condition_latents)
296
+