blanchon commited on
Commit
dc31968
·
verified ·
1 Parent(s): ece00c4

Create fluxdcgen_transformer.py

Browse files
Files changed (1) hide show
  1. transformer/fluxdcgen_transformer.py +846 -0
transformer/fluxdcgen_transformer.py ADDED
@@ -0,0 +1,846 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Black Forest Labs, The HuggingFace Team and The InstantX Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Dict, List, Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+
23
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
24
+ from diffusers.loaders import FluxTransformer2DLoadersMixin, FromOriginalModelMixin, PeftAdapterMixin
25
+ from diffusers.utils import USE_PEFT_BACKEND, is_torch_npu_available, logging, scale_lora_layers, unscale_lora_layers
26
+ from diffusers.utils.torch_utils import maybe_allow_in_graph
27
+ from diffusers.models._modeling_parallel import ContextParallelInput, ContextParallelOutput
28
+ from diffusers.models.attention import AttentionMixin, AttentionModuleMixin, FeedForward
29
+ from diffusers.models.attention_dispatch import dispatch_attention_fn
30
+ from diffusers.models.cache_utils import CacheMixin
31
+ from diffusers.models.embeddings import (
32
+ CombinedTimestepGuidanceTextProjEmbeddings,
33
+ CombinedTimestepTextProjEmbeddings,
34
+ apply_rotary_emb,
35
+ get_1d_rotary_pos_embed,
36
+ )
37
+ from diffusers.models.modeling_outputs import Transformer2DModelOutput
38
+ from diffusers.models.modeling_utils import ModelMixin
39
+ from diffusers.models.normalization import AdaLayerNormContinuous, AdaLayerNormZero, AdaLayerNormZeroSingle
40
+
41
+
42
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
43
+
44
+
45
+ def _get_projections(attn: "FluxAttention", hidden_states, encoder_hidden_states=None):
46
+ query = attn.to_q(hidden_states)
47
+ key = attn.to_k(hidden_states)
48
+ value = attn.to_v(hidden_states)
49
+
50
+ encoder_query = encoder_key = encoder_value = None
51
+ if encoder_hidden_states is not None and attn.added_kv_proj_dim is not None:
52
+ encoder_query = attn.add_q_proj(encoder_hidden_states)
53
+ encoder_key = attn.add_k_proj(encoder_hidden_states)
54
+ encoder_value = attn.add_v_proj(encoder_hidden_states)
55
+
56
+ return query, key, value, encoder_query, encoder_key, encoder_value
57
+
58
+
59
+ def _get_fused_projections(attn: "FluxAttention", hidden_states, encoder_hidden_states=None):
60
+ query, key, value = attn.to_qkv(hidden_states).chunk(3, dim=-1)
61
+
62
+ encoder_query = encoder_key = encoder_value = (None,)
63
+ if encoder_hidden_states is not None and hasattr(attn, "to_added_qkv"):
64
+ encoder_query, encoder_key, encoder_value = attn.to_added_qkv(encoder_hidden_states).chunk(3, dim=-1)
65
+
66
+ return query, key, value, encoder_query, encoder_key, encoder_value
67
+
68
+
69
+ def _get_qkv_projections(attn: "FluxAttention", hidden_states, encoder_hidden_states=None):
70
+ if attn.fused_projections:
71
+ return _get_fused_projections(attn, hidden_states, encoder_hidden_states)
72
+ return _get_projections(attn, hidden_states, encoder_hidden_states)
73
+
74
+
75
+ class FluxAttnProcessor:
76
+ _attention_backend = None
77
+ _parallel_config = None
78
+
79
+ def __init__(self):
80
+ if not hasattr(F, "scaled_dot_product_attention"):
81
+ raise ImportError(f"{self.__class__.__name__} requires PyTorch 2.0. Please upgrade your pytorch version.")
82
+
83
+ def __call__(
84
+ self,
85
+ attn: "FluxAttention",
86
+ hidden_states: torch.Tensor,
87
+ encoder_hidden_states: torch.Tensor = None,
88
+ attention_mask: Optional[torch.Tensor] = None,
89
+ image_rotary_emb: Optional[torch.Tensor] = None,
90
+ ) -> torch.Tensor:
91
+ query, key, value, encoder_query, encoder_key, encoder_value = _get_qkv_projections(
92
+ attn, hidden_states, encoder_hidden_states
93
+ )
94
+
95
+ query = query.unflatten(-1, (attn.heads, -1))
96
+ key = key.unflatten(-1, (attn.heads, -1))
97
+ value = value.unflatten(-1, (attn.heads, -1))
98
+
99
+ query = attn.norm_q(query)
100
+ key = attn.norm_k(key)
101
+
102
+ if attn.added_kv_proj_dim is not None:
103
+ encoder_query = encoder_query.unflatten(-1, (attn.heads, -1))
104
+ encoder_key = encoder_key.unflatten(-1, (attn.heads, -1))
105
+ encoder_value = encoder_value.unflatten(-1, (attn.heads, -1))
106
+
107
+ encoder_query = attn.norm_added_q(encoder_query)
108
+ encoder_key = attn.norm_added_k(encoder_key)
109
+
110
+ query = torch.cat([encoder_query, query], dim=1)
111
+ key = torch.cat([encoder_key, key], dim=1)
112
+ value = torch.cat([encoder_value, value], dim=1)
113
+
114
+ if image_rotary_emb is not None:
115
+ query = apply_rotary_emb(query, image_rotary_emb, sequence_dim=1)
116
+ key = apply_rotary_emb(key, image_rotary_emb, sequence_dim=1)
117
+
118
+ hidden_states = dispatch_attention_fn(
119
+ query,
120
+ key,
121
+ value,
122
+ attn_mask=attention_mask,
123
+ backend=self._attention_backend,
124
+ parallel_config=self._parallel_config,
125
+ )
126
+ hidden_states = hidden_states.flatten(2, 3)
127
+ hidden_states = hidden_states.to(query.dtype)
128
+
129
+ if encoder_hidden_states is not None:
130
+ encoder_hidden_states, hidden_states = hidden_states.split_with_sizes(
131
+ [encoder_hidden_states.shape[1], hidden_states.shape[1] - encoder_hidden_states.shape[1]], dim=1
132
+ )
133
+ hidden_states = attn.to_out[0](hidden_states)
134
+ hidden_states = attn.to_out[1](hidden_states)
135
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
136
+
137
+ return hidden_states, encoder_hidden_states
138
+ else:
139
+ return hidden_states
140
+
141
+
142
+ class FluxIPAdapterAttnProcessor(torch.nn.Module):
143
+ """Flux Attention processor for IP-Adapter."""
144
+
145
+ _attention_backend = None
146
+ _parallel_config = None
147
+
148
+ def __init__(
149
+ self, hidden_size: int, cross_attention_dim: int, num_tokens=(4,), scale=1.0, device=None, dtype=None
150
+ ):
151
+ super().__init__()
152
+
153
+ if not hasattr(F, "scaled_dot_product_attention"):
154
+ raise ImportError(
155
+ f"{self.__class__.__name__} requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
156
+ )
157
+
158
+ self.hidden_size = hidden_size
159
+ self.cross_attention_dim = cross_attention_dim
160
+
161
+ if not isinstance(num_tokens, (tuple, list)):
162
+ num_tokens = [num_tokens]
163
+
164
+ if not isinstance(scale, list):
165
+ scale = [scale] * len(num_tokens)
166
+ if len(scale) != len(num_tokens):
167
+ raise ValueError("`scale` should be a list of integers with the same length as `num_tokens`.")
168
+ self.scale = scale
169
+
170
+ self.to_k_ip = nn.ModuleList(
171
+ [
172
+ nn.Linear(cross_attention_dim, hidden_size, bias=True, device=device, dtype=dtype)
173
+ for _ in range(len(num_tokens))
174
+ ]
175
+ )
176
+ self.to_v_ip = nn.ModuleList(
177
+ [
178
+ nn.Linear(cross_attention_dim, hidden_size, bias=True, device=device, dtype=dtype)
179
+ for _ in range(len(num_tokens))
180
+ ]
181
+ )
182
+
183
+ def __call__(
184
+ self,
185
+ attn: "FluxAttention",
186
+ hidden_states: torch.Tensor,
187
+ encoder_hidden_states: torch.Tensor = None,
188
+ attention_mask: Optional[torch.Tensor] = None,
189
+ image_rotary_emb: Optional[torch.Tensor] = None,
190
+ ip_hidden_states: Optional[List[torch.Tensor]] = None,
191
+ ip_adapter_masks: Optional[torch.Tensor] = None,
192
+ ) -> torch.Tensor:
193
+ batch_size = hidden_states.shape[0]
194
+
195
+ query, key, value, encoder_query, encoder_key, encoder_value = _get_qkv_projections(
196
+ attn, hidden_states, encoder_hidden_states
197
+ )
198
+
199
+ query = query.unflatten(-1, (attn.heads, -1))
200
+ key = key.unflatten(-1, (attn.heads, -1))
201
+ value = value.unflatten(-1, (attn.heads, -1))
202
+
203
+ query = attn.norm_q(query)
204
+ key = attn.norm_k(key)
205
+ ip_query = query
206
+
207
+ if encoder_hidden_states is not None:
208
+ encoder_query = encoder_query.unflatten(-1, (attn.heads, -1))
209
+ encoder_key = encoder_key.unflatten(-1, (attn.heads, -1))
210
+ encoder_value = encoder_value.unflatten(-1, (attn.heads, -1))
211
+
212
+ encoder_query = attn.norm_added_q(encoder_query)
213
+ encoder_key = attn.norm_added_k(encoder_key)
214
+
215
+ query = torch.cat([encoder_query, query], dim=1)
216
+ key = torch.cat([encoder_key, key], dim=1)
217
+ value = torch.cat([encoder_value, value], dim=1)
218
+
219
+ if image_rotary_emb is not None:
220
+ query = apply_rotary_emb(query, image_rotary_emb, sequence_dim=1)
221
+ key = apply_rotary_emb(key, image_rotary_emb, sequence_dim=1)
222
+
223
+ hidden_states = dispatch_attention_fn(
224
+ query,
225
+ key,
226
+ value,
227
+ attn_mask=attention_mask,
228
+ dropout_p=0.0,
229
+ is_causal=False,
230
+ backend=self._attention_backend,
231
+ parallel_config=self._parallel_config,
232
+ )
233
+ hidden_states = hidden_states.flatten(2, 3)
234
+ hidden_states = hidden_states.to(query.dtype)
235
+
236
+ if encoder_hidden_states is not None:
237
+ encoder_hidden_states, hidden_states = hidden_states.split_with_sizes(
238
+ [encoder_hidden_states.shape[1], hidden_states.shape[1] - encoder_hidden_states.shape[1]], dim=1
239
+ )
240
+ hidden_states = attn.to_out[0](hidden_states)
241
+ hidden_states = attn.to_out[1](hidden_states)
242
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
243
+
244
+ # IP-adapter
245
+ ip_attn_output = torch.zeros_like(hidden_states)
246
+
247
+ for current_ip_hidden_states, scale, to_k_ip, to_v_ip in zip(
248
+ ip_hidden_states, self.scale, self.to_k_ip, self.to_v_ip
249
+ ):
250
+ ip_key = to_k_ip(current_ip_hidden_states)
251
+ ip_value = to_v_ip(current_ip_hidden_states)
252
+
253
+ ip_key = ip_key.view(batch_size, -1, attn.heads, attn.head_dim)
254
+ ip_value = ip_value.view(batch_size, -1, attn.heads, attn.head_dim)
255
+
256
+ current_ip_hidden_states = dispatch_attention_fn(
257
+ ip_query,
258
+ ip_key,
259
+ ip_value,
260
+ attn_mask=None,
261
+ dropout_p=0.0,
262
+ is_causal=False,
263
+ backend=self._attention_backend,
264
+ parallel_config=self._parallel_config,
265
+ )
266
+ current_ip_hidden_states = current_ip_hidden_states.reshape(batch_size, -1, attn.heads * attn.head_dim)
267
+ current_ip_hidden_states = current_ip_hidden_states.to(ip_query.dtype)
268
+ ip_attn_output += scale * current_ip_hidden_states
269
+
270
+ return hidden_states, encoder_hidden_states, ip_attn_output
271
+ else:
272
+ return hidden_states
273
+
274
+
275
+ class FluxAttention(torch.nn.Module, AttentionModuleMixin):
276
+ _default_processor_cls = FluxAttnProcessor
277
+ _available_processors = [
278
+ FluxAttnProcessor,
279
+ FluxIPAdapterAttnProcessor,
280
+ ]
281
+
282
+ def __init__(
283
+ self,
284
+ query_dim: int,
285
+ heads: int = 8,
286
+ dim_head: int = 64,
287
+ dropout: float = 0.0,
288
+ bias: bool = False,
289
+ added_kv_proj_dim: Optional[int] = None,
290
+ added_proj_bias: Optional[bool] = True,
291
+ out_bias: bool = True,
292
+ eps: float = 1e-5,
293
+ out_dim: int = None,
294
+ context_pre_only: Optional[bool] = None,
295
+ pre_only: bool = False,
296
+ elementwise_affine: bool = True,
297
+ processor=None,
298
+ ):
299
+ super().__init__()
300
+
301
+ self.head_dim = dim_head
302
+ self.inner_dim = out_dim if out_dim is not None else dim_head * heads
303
+ self.query_dim = query_dim
304
+ self.use_bias = bias
305
+ self.dropout = dropout
306
+ self.out_dim = out_dim if out_dim is not None else query_dim
307
+ self.context_pre_only = context_pre_only
308
+ self.pre_only = pre_only
309
+ self.heads = out_dim // dim_head if out_dim is not None else heads
310
+ self.added_kv_proj_dim = added_kv_proj_dim
311
+ self.added_proj_bias = added_proj_bias
312
+
313
+ self.norm_q = torch.nn.RMSNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
314
+ self.norm_k = torch.nn.RMSNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
315
+ self.to_q = torch.nn.Linear(query_dim, self.inner_dim, bias=bias)
316
+ self.to_k = torch.nn.Linear(query_dim, self.inner_dim, bias=bias)
317
+ self.to_v = torch.nn.Linear(query_dim, self.inner_dim, bias=bias)
318
+
319
+ if not self.pre_only:
320
+ self.to_out = torch.nn.ModuleList([])
321
+ self.to_out.append(torch.nn.Linear(self.inner_dim, self.out_dim, bias=out_bias))
322
+ self.to_out.append(torch.nn.Dropout(dropout))
323
+
324
+ if added_kv_proj_dim is not None:
325
+ self.norm_added_q = torch.nn.RMSNorm(dim_head, eps=eps)
326
+ self.norm_added_k = torch.nn.RMSNorm(dim_head, eps=eps)
327
+ self.add_q_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias)
328
+ self.add_k_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias)
329
+ self.add_v_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias)
330
+ self.to_add_out = torch.nn.Linear(self.inner_dim, query_dim, bias=out_bias)
331
+
332
+ if processor is None:
333
+ processor = self._default_processor_cls()
334
+ self.set_processor(processor)
335
+
336
+ def forward(
337
+ self,
338
+ hidden_states: torch.Tensor,
339
+ encoder_hidden_states: Optional[torch.Tensor] = None,
340
+ attention_mask: Optional[torch.Tensor] = None,
341
+ image_rotary_emb: Optional[torch.Tensor] = None,
342
+ **kwargs,
343
+ ) -> torch.Tensor:
344
+ attn_parameters = set(inspect.signature(self.processor.__call__).parameters.keys())
345
+ quiet_attn_parameters = {"ip_adapter_masks", "ip_hidden_states"}
346
+ unused_kwargs = [k for k, _ in kwargs.items() if k not in attn_parameters and k not in quiet_attn_parameters]
347
+ if len(unused_kwargs) > 0:
348
+ logger.warning(
349
+ f"joint_attention_kwargs {unused_kwargs} are not expected by {self.processor.__class__.__name__} and will be ignored."
350
+ )
351
+ kwargs = {k: w for k, w in kwargs.items() if k in attn_parameters}
352
+ return self.processor(self, hidden_states, encoder_hidden_states, attention_mask, image_rotary_emb, **kwargs)
353
+
354
+
355
+ @maybe_allow_in_graph
356
+ class FluxSingleTransformerBlock(nn.Module):
357
+ def __init__(self, dim: int, num_attention_heads: int, attention_head_dim: int, mlp_ratio: float = 4.0):
358
+ super().__init__()
359
+ self.mlp_hidden_dim = int(dim * mlp_ratio)
360
+
361
+ self.norm = AdaLayerNormZeroSingle(dim)
362
+ self.proj_mlp = nn.Linear(dim, self.mlp_hidden_dim)
363
+ self.act_mlp = nn.GELU(approximate="tanh")
364
+ self.proj_out = nn.Linear(dim + self.mlp_hidden_dim, dim)
365
+
366
+ self.attn = FluxAttention(
367
+ query_dim=dim,
368
+ dim_head=attention_head_dim,
369
+ heads=num_attention_heads,
370
+ out_dim=dim,
371
+ bias=True,
372
+ processor=FluxAttnProcessor(),
373
+ eps=1e-6,
374
+ pre_only=True,
375
+ )
376
+
377
+ def forward(
378
+ self,
379
+ hidden_states: torch.Tensor,
380
+ encoder_hidden_states: torch.Tensor,
381
+ temb: torch.Tensor,
382
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
383
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
384
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
385
+ text_seq_len = encoder_hidden_states.shape[1]
386
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
387
+
388
+ residual = hidden_states
389
+ norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
390
+ mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
391
+ joint_attention_kwargs = joint_attention_kwargs or {}
392
+ attn_output = self.attn(
393
+ hidden_states=norm_hidden_states,
394
+ image_rotary_emb=image_rotary_emb,
395
+ **joint_attention_kwargs,
396
+ )
397
+
398
+ hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
399
+ gate = gate.unsqueeze(1)
400
+ hidden_states = gate * self.proj_out(hidden_states)
401
+ hidden_states = residual + hidden_states
402
+ if hidden_states.dtype == torch.float16:
403
+ hidden_states = hidden_states.clip(-65504, 65504)
404
+
405
+ encoder_hidden_states, hidden_states = hidden_states[:, :text_seq_len], hidden_states[:, text_seq_len:]
406
+ return encoder_hidden_states, hidden_states
407
+
408
+
409
+ @maybe_allow_in_graph
410
+ class FluxTransformerBlock(nn.Module):
411
+ def __init__(
412
+ self, dim: int, num_attention_heads: int, attention_head_dim: int, qk_norm: str = "rms_norm", eps: float = 1e-6
413
+ ):
414
+ super().__init__()
415
+
416
+ self.norm1 = AdaLayerNormZero(dim)
417
+ self.norm1_context = AdaLayerNormZero(dim)
418
+
419
+ self.attn = FluxAttention(
420
+ query_dim=dim,
421
+ added_kv_proj_dim=dim,
422
+ dim_head=attention_head_dim,
423
+ heads=num_attention_heads,
424
+ out_dim=dim,
425
+ context_pre_only=False,
426
+ bias=True,
427
+ processor=FluxAttnProcessor(),
428
+ eps=eps,
429
+ )
430
+
431
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
432
+ self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
433
+
434
+ self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
435
+ self.ff_context = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
436
+
437
+ def forward(
438
+ self,
439
+ hidden_states: torch.Tensor,
440
+ encoder_hidden_states: torch.Tensor,
441
+ temb: torch.Tensor,
442
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
443
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
444
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
445
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
446
+
447
+ norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
448
+ encoder_hidden_states, emb=temb
449
+ )
450
+ joint_attention_kwargs = joint_attention_kwargs or {}
451
+
452
+ # Attention.
453
+ attention_outputs = self.attn(
454
+ hidden_states=norm_hidden_states,
455
+ encoder_hidden_states=norm_encoder_hidden_states,
456
+ image_rotary_emb=image_rotary_emb,
457
+ **joint_attention_kwargs,
458
+ )
459
+
460
+ if len(attention_outputs) == 2:
461
+ attn_output, context_attn_output = attention_outputs
462
+ elif len(attention_outputs) == 3:
463
+ attn_output, context_attn_output, ip_attn_output = attention_outputs
464
+
465
+ # Process attention outputs for the `hidden_states`.
466
+ attn_output = gate_msa.unsqueeze(1) * attn_output
467
+ hidden_states = hidden_states + attn_output
468
+
469
+ norm_hidden_states = self.norm2(hidden_states)
470
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
471
+
472
+ ff_output = self.ff(norm_hidden_states)
473
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
474
+
475
+ hidden_states = hidden_states + ff_output
476
+ if len(attention_outputs) == 3:
477
+ hidden_states = hidden_states + ip_attn_output
478
+
479
+ # Process attention outputs for the `encoder_hidden_states`.
480
+ context_attn_output = c_gate_msa.unsqueeze(1) * context_attn_output
481
+ encoder_hidden_states = encoder_hidden_states + context_attn_output
482
+
483
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
484
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
485
+
486
+ context_ff_output = self.ff_context(norm_encoder_hidden_states)
487
+ encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
488
+ if encoder_hidden_states.dtype == torch.float16:
489
+ encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
490
+
491
+ return encoder_hidden_states, hidden_states
492
+
493
+
494
+ class FluxPosEmbed(nn.Module):
495
+ # modified from https://github.com/black-forest-labs/flux/blob/c00d7c60b085fce8058b9df845e036090873f2ce/src/flux/modules/layers.py#L11
496
+ def __init__(self, theta: int, axes_dim: List[int]):
497
+ super().__init__()
498
+ self.theta = theta
499
+ self.axes_dim = axes_dim
500
+
501
+ def forward(self, ids: torch.Tensor) -> torch.Tensor:
502
+ n_axes = ids.shape[-1]
503
+ cos_out = []
504
+ sin_out = []
505
+ pos = ids.float()
506
+ is_mps = ids.device.type == "mps"
507
+ is_npu = ids.device.type == "npu"
508
+ freqs_dtype = torch.float32 if (is_mps or is_npu) else torch.float64
509
+ for i in range(n_axes):
510
+ cos, sin = get_1d_rotary_pos_embed(
511
+ self.axes_dim[i],
512
+ pos[:, i],
513
+ theta=self.theta,
514
+ repeat_interleave_real=True,
515
+ use_real=True,
516
+ freqs_dtype=freqs_dtype,
517
+ )
518
+ cos_out.append(cos)
519
+ sin_out.append(sin)
520
+ freqs_cos = torch.cat(cos_out, dim=-1).to(ids.device)
521
+ freqs_sin = torch.cat(sin_out, dim=-1).to(ids.device)
522
+ return freqs_cos, freqs_sin
523
+
524
+
525
+ class DCFluxTransformer2DModel(
526
+ ModelMixin,
527
+ ConfigMixin,
528
+ PeftAdapterMixin,
529
+ FromOriginalModelMixin,
530
+ FluxTransformer2DLoadersMixin,
531
+ CacheMixin,
532
+ AttentionMixin,
533
+ ):
534
+ """
535
+ The Transformer model introduced in Flux.
536
+
537
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
538
+
539
+ Args:
540
+ patch_size (`int`, defaults to `1`):
541
+ Patch size to turn the input data into small patches.
542
+ in_channels (`int`, defaults to `64`):
543
+ The number of channels in the input.
544
+ out_channels (`int`, *optional*, defaults to `None`):
545
+ The number of channels in the output. If not specified, it defaults to `in_channels`.
546
+ num_layers (`int`, defaults to `19`):
547
+ The number of layers of dual stream DiT blocks to use.
548
+ num_single_layers (`int`, defaults to `38`):
549
+ The number of layers of single stream DiT blocks to use.
550
+ attention_head_dim (`int`, defaults to `128`):
551
+ The number of dimensions to use for each attention head.
552
+ num_attention_heads (`int`, defaults to `24`):
553
+ The number of attention heads to use.
554
+ joint_attention_dim (`int`, defaults to `4096`):
555
+ The number of dimensions to use for the joint attention (embedding/channel dimension of
556
+ `encoder_hidden_states`).
557
+ pooled_projection_dim (`int`, defaults to `768`):
558
+ The number of dimensions to use for the pooled projection.
559
+ guidance_embeds (`bool`, defaults to `False`):
560
+ Whether to use guidance embeddings for guidance-distilled variant of the model.
561
+ axes_dims_rope (`Tuple[int]`, defaults to `(16, 56, 56)`):
562
+ The dimensions to use for the rotary positional embeddings.
563
+ """
564
+
565
+ _supports_gradient_checkpointing = True
566
+ _no_split_modules = ["FluxTransformerBlock", "FluxSingleTransformerBlock"]
567
+ _skip_layerwise_casting_patterns = ["pos_embed", "norm"]
568
+ _repeated_blocks = ["FluxTransformerBlock", "FluxSingleTransformerBlock"]
569
+ _cp_plan = {
570
+ "": {
571
+ "hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
572
+ "encoder_hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
573
+ "img_ids": ContextParallelInput(split_dim=0, expected_dims=2, split_output=False),
574
+ "txt_ids": ContextParallelInput(split_dim=0, expected_dims=2, split_output=False),
575
+ },
576
+ "proj_out": ContextParallelOutput(gather_dim=1, expected_dims=3),
577
+ }
578
+
579
+ @register_to_config
580
+ def __init__(
581
+ self,
582
+ patch_size: int = 1,
583
+ in_channels: int = 64,
584
+ out_channels: Optional[int] = None,
585
+ num_layers: int = 19,
586
+ num_single_layers: int = 38,
587
+ attention_head_dim: int = 128,
588
+ num_attention_heads: int = 24,
589
+ joint_attention_dim: int = 4096,
590
+ pooled_projection_dim: int = 768,
591
+ guidance_embeds: bool = False,
592
+ axes_dims_rope: Tuple[int, int, int] = (16, 56, 56),
593
+ ):
594
+ super().__init__()
595
+ self.out_channels = out_channels or in_channels
596
+ self.inner_dim = num_attention_heads * attention_head_dim
597
+
598
+ self.pos_embed = FluxPosEmbed(theta=10000, axes_dim=axes_dims_rope)
599
+
600
+ text_time_guidance_cls = (
601
+ CombinedTimestepGuidanceTextProjEmbeddings if guidance_embeds else CombinedTimestepTextProjEmbeddings
602
+ )
603
+ self.time_text_embed = text_time_guidance_cls(
604
+ embedding_dim=self.inner_dim, pooled_projection_dim=pooled_projection_dim
605
+ )
606
+
607
+ self.context_embedder = nn.Linear(joint_attention_dim, self.inner_dim)
608
+ self.x_embedder = nn.Linear(in_channels, self.inner_dim)
609
+
610
+ self.transformer_blocks = nn.ModuleList(
611
+ [
612
+ FluxTransformerBlock(
613
+ dim=self.inner_dim,
614
+ num_attention_heads=num_attention_heads,
615
+ attention_head_dim=attention_head_dim,
616
+ )
617
+ for _ in range(num_layers)
618
+ ]
619
+ )
620
+
621
+ self.single_transformer_blocks = nn.ModuleList(
622
+ [
623
+ FluxSingleTransformerBlock(
624
+ dim=self.inner_dim,
625
+ num_attention_heads=num_attention_heads,
626
+ attention_head_dim=attention_head_dim,
627
+ )
628
+ for _ in range(num_single_layers)
629
+ ]
630
+ )
631
+
632
+ self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
633
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
634
+
635
+ t5_null_embedding = torch.zeros(256, 4096, dtype=torch.bfloat16, requires_grad=False)
636
+ clip_null_embedding = torch.zeros(768, dtype=torch.bfloat16, requires_grad=False)
637
+ self.register_buffer("t5_null_embedding", t5_null_embedding, persistent=True)
638
+ self.register_buffer("clip_null_embedding", clip_null_embedding, persistent=True)
639
+
640
+ self.gradient_checkpointing = False
641
+
642
+ def has_null_embeddings(self) -> bool:
643
+ return self.t5_null_embedding.numel() > 0 and self.clip_null_embedding.numel() > 0
644
+
645
+ def get_null_embeddings(self, batch_size: int = 1, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None):
646
+ """
647
+ Get null embeddings expanded for batch size.
648
+
649
+ Args:
650
+ batch_size: Batch size to expand embeddings to
651
+ device: Device to move embeddings to (defaults to transformer's device)
652
+ dtype: Data type to cast embeddings to (defaults to transformer's dtype)
653
+
654
+ Returns:
655
+ Tuple of (t5_null_embedding, clip_null_embedding, text_ids)
656
+ """
657
+ if not self.has_null_embeddings():
658
+ raise ValueError(
659
+ "Null embeddings not set. This model requires null embeddings for proper CFG. "
660
+ "Load with from_pretrained_with_null_embeddings() or call set_null_embeddings()."
661
+ )
662
+
663
+ device = device or next(self.parameters()).device
664
+ dtype = dtype or next(self.parameters()).dtype
665
+
666
+ # Get null embeddings
667
+ t5_null = self.t5_null_embedding.to(device=device, dtype=dtype)
668
+ clip_null = self.clip_null_embedding.to(device=device, dtype=dtype)
669
+
670
+ # Expand for batch size if needed
671
+ if t5_null.shape[0] == 1 and batch_size > 1:
672
+ t5_null = t5_null.repeat(batch_size, 1, 1)
673
+
674
+ if clip_null.shape[0] == 1 and batch_size > 1:
675
+ clip_null = clip_null.repeat(batch_size, 1)
676
+
677
+ # Create text_ids for negative prompts
678
+ text_ids = torch.zeros(t5_null.shape[1], 3, device=device, dtype=dtype)
679
+
680
+ return t5_null, clip_null, text_ids
681
+
682
+
683
+
684
+ def forward(
685
+ self,
686
+ hidden_states: torch.Tensor,
687
+ encoder_hidden_states: torch.Tensor = None,
688
+ pooled_projections: torch.Tensor = None,
689
+ timestep: torch.LongTensor = None,
690
+ img_ids: torch.Tensor = None,
691
+ txt_ids: torch.Tensor = None,
692
+ guidance: torch.Tensor = None,
693
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
694
+ controlnet_block_samples=None,
695
+ controlnet_single_block_samples=None,
696
+ return_dict: bool = True,
697
+ controlnet_blocks_repeat: bool = False,
698
+ ) -> Union[torch.Tensor, Transformer2DModelOutput]:
699
+ """
700
+ The [`FluxTransformer2DModel`] forward method.
701
+
702
+ Args:
703
+ hidden_states (`torch.Tensor` of shape `(batch_size, image_sequence_length, in_channels)`):
704
+ Input `hidden_states`.
705
+ encoder_hidden_states (`torch.Tensor` of shape `(batch_size, text_sequence_length, joint_attention_dim)`):
706
+ Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
707
+ pooled_projections (`torch.Tensor` of shape `(batch_size, projection_dim)`): Embeddings projected
708
+ from the embeddings of input conditions.
709
+ timestep ( `torch.LongTensor`):
710
+ Used to indicate denoising step.
711
+ block_controlnet_hidden_states: (`list` of `torch.Tensor`):
712
+ A list of tensors that if specified are added to the residuals of transformer blocks.
713
+ joint_attention_kwargs (`dict`, *optional*):
714
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
715
+ `self.processor` in
716
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
717
+ return_dict (`bool`, *optional*, defaults to `True`):
718
+ Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
719
+ tuple.
720
+
721
+ Returns:
722
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
723
+ `tuple` where the first element is the sample tensor.
724
+ """
725
+ if joint_attention_kwargs is not None:
726
+ joint_attention_kwargs = joint_attention_kwargs.copy()
727
+ lora_scale = joint_attention_kwargs.pop("scale", 1.0)
728
+ else:
729
+ lora_scale = 1.0
730
+
731
+ if USE_PEFT_BACKEND:
732
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
733
+ scale_lora_layers(self, lora_scale)
734
+ else:
735
+ if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
736
+ logger.warning(
737
+ "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
738
+ )
739
+
740
+ hidden_states = self.x_embedder(hidden_states)
741
+
742
+ timestep = timestep.to(hidden_states.dtype) * 1000
743
+ if guidance is not None:
744
+ guidance = guidance.to(hidden_states.dtype) * 1000
745
+
746
+ temb = (
747
+ self.time_text_embed(timestep, pooled_projections)
748
+ if guidance is None
749
+ else self.time_text_embed(timestep, guidance, pooled_projections)
750
+ )
751
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
752
+
753
+ if txt_ids.ndim == 3:
754
+ logger.warning(
755
+ "Passing `txt_ids` 3d torch.Tensor is deprecated."
756
+ "Please remove the batch dimension and pass it as a 2d torch Tensor"
757
+ )
758
+ txt_ids = txt_ids[0]
759
+ if img_ids.ndim == 3:
760
+ logger.warning(
761
+ "Passing `img_ids` 3d torch.Tensor is deprecated."
762
+ "Please remove the batch dimension and pass it as a 2d torch Tensor"
763
+ )
764
+ img_ids = img_ids[0]
765
+
766
+ ids = torch.cat((txt_ids, img_ids), dim=0)
767
+ if is_torch_npu_available():
768
+ freqs_cos, freqs_sin = self.pos_embed(ids.cpu())
769
+ image_rotary_emb = (freqs_cos.npu(), freqs_sin.npu())
770
+ else:
771
+ image_rotary_emb = self.pos_embed(ids)
772
+
773
+ if joint_attention_kwargs is not None and "ip_adapter_image_embeds" in joint_attention_kwargs:
774
+ ip_adapter_image_embeds = joint_attention_kwargs.pop("ip_adapter_image_embeds")
775
+ ip_hidden_states = self.encoder_hid_proj(ip_adapter_image_embeds)
776
+ joint_attention_kwargs.update({"ip_hidden_states": ip_hidden_states})
777
+
778
+ for index_block, block in enumerate(self.transformer_blocks):
779
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
780
+ encoder_hidden_states, hidden_states = self._gradient_checkpointing_func(
781
+ block,
782
+ hidden_states,
783
+ encoder_hidden_states,
784
+ temb,
785
+ image_rotary_emb,
786
+ joint_attention_kwargs,
787
+ )
788
+
789
+ else:
790
+ encoder_hidden_states, hidden_states = block(
791
+ hidden_states=hidden_states,
792
+ encoder_hidden_states=encoder_hidden_states,
793
+ temb=temb,
794
+ image_rotary_emb=image_rotary_emb,
795
+ joint_attention_kwargs=joint_attention_kwargs,
796
+ )
797
+
798
+ # controlnet residual
799
+ if controlnet_block_samples is not None:
800
+ interval_control = len(self.transformer_blocks) / len(controlnet_block_samples)
801
+ interval_control = int(np.ceil(interval_control))
802
+ # For Xlabs ControlNet.
803
+ if controlnet_blocks_repeat:
804
+ hidden_states = (
805
+ hidden_states + controlnet_block_samples[index_block % len(controlnet_block_samples)]
806
+ )
807
+ else:
808
+ hidden_states = hidden_states + controlnet_block_samples[index_block // interval_control]
809
+
810
+ for index_block, block in enumerate(self.single_transformer_blocks):
811
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
812
+ encoder_hidden_states, hidden_states = self._gradient_checkpointing_func(
813
+ block,
814
+ hidden_states,
815
+ encoder_hidden_states,
816
+ temb,
817
+ image_rotary_emb,
818
+ joint_attention_kwargs,
819
+ )
820
+
821
+ else:
822
+ encoder_hidden_states, hidden_states = block(
823
+ hidden_states=hidden_states,
824
+ encoder_hidden_states=encoder_hidden_states,
825
+ temb=temb,
826
+ image_rotary_emb=image_rotary_emb,
827
+ joint_attention_kwargs=joint_attention_kwargs,
828
+ )
829
+
830
+ # controlnet residual
831
+ if controlnet_single_block_samples is not None:
832
+ interval_control = len(self.single_transformer_blocks) / len(controlnet_single_block_samples)
833
+ interval_control = int(np.ceil(interval_control))
834
+ hidden_states = hidden_states + controlnet_single_block_samples[index_block // interval_control]
835
+
836
+ hidden_states = self.norm_out(hidden_states, temb)
837
+ output = self.proj_out(hidden_states)
838
+
839
+ if USE_PEFT_BACKEND:
840
+ # remove `lora_scale` from each PEFT layer
841
+ unscale_lora_layers(self, lora_scale)
842
+
843
+ if not return_dict:
844
+ return (output,)
845
+
846
+ return Transformer2DModelOutput(sample=output)