nupurkmr9 commited on
Commit
a30afc5
Β·
verified Β·
1 Parent(s): adbaa1e

Update pipelines/flux_pipeline/transformer.py

Browse files
pipelines/flux_pipeline/transformer.py CHANGED
@@ -6,14 +6,11 @@
6
 
7
  import math
8
  from contextlib import contextmanager
9
- from typing import Any, Dict, List, Optional, Tuple, Union
10
 
11
  import torch
12
  import torch.nn as nn
13
  import torch.nn.functional as F
14
- from einops import rearrange
15
- from peft.tuners.lora.layer import LoraLayer
16
-
17
  from diffusers.configuration_utils import ConfigMixin, register_to_config
18
  from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
19
  from diffusers.models.attention import FeedForward
@@ -38,9 +35,20 @@ from diffusers.utils import (
38
  unscale_lora_layers,
39
  )
40
  from diffusers.utils.torch_utils import maybe_allow_in_graph
 
 
 
 
 
 
 
 
 
41
 
42
  logger = logging.get_logger(__name__) # pylint: disable=invalid-name
43
 
 
 
44
 
45
  class FluxAttnProcessor2_0:
46
  """Attention processor used typically in processing the SD3-like self-attention projections."""
@@ -59,18 +67,12 @@ class FluxAttnProcessor2_0:
59
  encoder_hidden_states: torch.FloatTensor = None,
60
  attention_mask: Optional[torch.FloatTensor] = None,
61
  image_rotary_emb: Optional[torch.Tensor] = None,
62
- shared_attn: bool=False, num=2,
63
- mode="a",
64
- ref_dict: dict = None,
65
- single: bool=False,
66
  scale: float = 1.0,
67
  timestep: float = 0,
68
- val: bool = False,
69
  neg_mode: bool = False,
70
  ) -> torch.FloatTensor:
71
- if mode == 'w': # and single:
72
- ref_dict[self.name] = hidden_states.detach()
73
-
74
  batch_size, _, _ = (
75
  hidden_states.shape
76
  if encoder_hidden_states is None
@@ -115,13 +117,48 @@ class FluxAttnProcessor2_0:
115
  query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
116
  key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
117
  value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
118
-
119
  if image_rotary_emb is not None:
120
  from diffusers.models.embeddings import apply_rotary_emb
121
- query = apply_rotary_emb(query, image_rotary_emb)
122
- key = apply_rotary_emb(key, image_rotary_emb)
123
-
124
- if neg_mode:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  res = int(math.sqrt((end_of_hidden_states-(text_seq if encoder_hidden_states is None else 0)) // num))
126
  hw = res*res
127
  mask_ = torch.zeros(1, res, num*res, res, num*res).to(query.device)
@@ -132,16 +169,19 @@ class FluxAttnProcessor2_0:
132
  mask[:, 512:, 512:] = mask_
133
  mask = mask.bool()
134
  mask = rearrange(mask.unsqueeze(0).expand(attn.heads, -1, -1, -1), "nh b ... -> b nh ...")
135
-
136
- hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False, attn_mask=mask)
137
- hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
 
 
 
138
 
139
  hidden_states = hidden_states.to(query.dtype)
140
 
141
  if encoder_hidden_states is not None:
142
  encoder_hidden_states, hidden_states = (
143
  hidden_states[:, : encoder_hidden_states.shape[1]],
144
- hidden_states[:, encoder_hidden_states.shape[1] : ],
145
  )
146
  hidden_states = hidden_states[:, :end_of_hidden_states]
147
 
@@ -207,15 +247,15 @@ class FluxSingleTransformerBlock(nn.Module):
207
  image_rotary_emb=None,
208
  joint_attention_kwargs: Optional[Dict[str, Any]] = None,
209
  ):
 
210
  residual = hidden_states
211
  norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
212
  mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
213
 
214
  attn_output = self.attn(
215
- hidden_states=norm_hidden_states,
216
  image_rotary_emb=image_rotary_emb,
217
  **joint_attention_kwargs,
218
- single=True,
219
  )
220
 
221
  hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
@@ -277,17 +317,16 @@ class FluxTransformerBlock(nn.Module):
277
  image_rotary_emb=None,
278
  joint_attention_kwargs: Optional[Dict[str, Any]] = None
279
  ):
 
280
  norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
281
-
282
  norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = (self.norm1_context(encoder_hidden_states, emb=temb))
283
 
284
  # Attention.
285
  attn_output, context_attn_output = self.attn(
286
- hidden_states=norm_hidden_states,
287
- encoder_hidden_states=norm_encoder_hidden_states,
288
  image_rotary_emb=image_rotary_emb,
289
  **joint_attention_kwargs,
290
- single=False,
291
  )
292
 
293
  # Process attention outputs for the `hidden_states`.
@@ -339,7 +378,8 @@ def set_adapter_scale(model, alpha):
339
  # restore original scaling values after exiting the context
340
  for module, scaling in original_scaling.items():
341
  module.scaling = scaling
342
-
 
343
  class FluxTransformer2DModelWithMasking(
344
  ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin
345
  ):
@@ -453,7 +493,7 @@ class FluxTransformer2DModelWithMasking(
453
  fn_recursive_add_processors(name, module, processors)
454
 
455
  return processors
456
-
457
  def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
458
  r"""
459
  Sets the attention processor to use to compute attention.
@@ -566,9 +606,7 @@ class FluxTransformer2DModelWithMasking(
566
  if img_ids.ndim == 3:
567
  img_ids = img_ids[0]
568
 
569
-
570
- # txt_ids = torch.zeros((1024,3)).to(txt_ids.device, dtype=txt_ids.dtype)
571
- ids = torch.cat((txt_ids, img_ids), dim=0)
572
 
573
  image_rotary_emb = self.pos_embed(ids)
574
 
@@ -644,7 +682,7 @@ class FluxTransformer2DModelWithMasking(
644
  joint_attention_kwargs=joint_attention_kwargs,
645
  )
646
 
647
- hidden_states = hidden_states[:, encoder_hidden_states.shape[1] :, ...]
648
 
649
  hidden_states = self.norm_out(hidden_states, temb)
650
  output = self.proj_out(hidden_states)
 
6
 
7
  import math
8
  from contextlib import contextmanager
9
+ from typing import Any, Dict, Optional, Tuple, Union
10
 
11
  import torch
12
  import torch.nn as nn
13
  import torch.nn.functional as F
 
 
 
14
  from diffusers.configuration_utils import ConfigMixin, register_to_config
15
  from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
16
  from diffusers.models.attention import FeedForward
 
35
  unscale_lora_layers,
36
  )
37
  from diffusers.utils.torch_utils import maybe_allow_in_graph
38
+ from einops import rearrange
39
+ from peft.tuners.lora.layer import LoraLayer
40
+
41
+ # Import flex_attention for optimized attention with fixed masks
42
+ try:
43
+ from torch.nn.attention.flex_attention import flex_attention, create_block_mask
44
+ FLEX_ATTENTION_AVAILABLE = True
45
+ except ImportError:
46
+ FLEX_ATTENTION_AVAILABLE = False
47
 
48
  logger = logging.get_logger(__name__) # pylint: disable=invalid-name
49
 
50
+ flex_attention_func = None
51
+ block_mask = None
52
 
53
  class FluxAttnProcessor2_0:
54
  """Attention processor used typically in processing the SD3-like self-attention projections."""
 
67
  encoder_hidden_states: torch.FloatTensor = None,
68
  attention_mask: Optional[torch.FloatTensor] = None,
69
  image_rotary_emb: Optional[torch.Tensor] = None,
70
+ shared_attn: bool = False, num=2,
 
 
 
71
  scale: float = 1.0,
72
  timestep: float = 0,
 
73
  neg_mode: bool = False,
74
  ) -> torch.FloatTensor:
75
+
 
 
76
  batch_size, _, _ = (
77
  hidden_states.shape
78
  if encoder_hidden_states is None
 
117
  query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
118
  key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
119
  value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
120
+
121
  if image_rotary_emb is not None:
122
  from diffusers.models.embeddings import apply_rotary_emb
123
+ query = apply_rotary_emb(query, image_rotary_emb).to(hidden_states.dtype)
124
+ key = apply_rotary_emb(key, image_rotary_emb).to(hidden_states.dtype)
125
+
126
+ if neg_mode and FLEX_ATTENTION_AVAILABLE:
127
+ # Apply flex_attention with the block mask
128
+ global flex_attention_func, block_mask
129
+ if flex_attention_func is None:
130
+ flex_attention_func = torch.compile(flex_attention, dynamic=False)
131
+ res = int(math.sqrt((end_of_hidden_states-(text_seq if encoder_hidden_states is None else 0)) // num))
132
+ seq_len = query.shape[2]
133
+
134
+ def block_diagonal_mask(b, h, q_idx, kv_idx):
135
+ text_offset = 512
136
+ # Text tokens (first 512) can attend to everything
137
+ # Use tensor operations instead of if statements
138
+ is_text = (q_idx < text_offset) | (kv_idx < text_offset)
139
+
140
+ # For spatial tokens, compute which block they belong to
141
+ q_spatial = q_idx - text_offset
142
+ kv_spatial = kv_idx - text_offset
143
+
144
+ # Determine block indices
145
+ q_block = (q_spatial // res) % num
146
+ kv_block = (kv_spatial // res) % num
147
+
148
+ # Only attend within the same block
149
+ same_block = (q_block == kv_block)
150
+
151
+ # Return: text can attend to everything OR same block
152
+ return is_text | same_block
153
+
154
+ # Create block mask for efficiency
155
+ block_mask = create_block_mask(block_diagonal_mask, B=1, H=None,
156
+ Q_LEN=seq_len, KV_LEN=seq_len, device=query.device)
157
+
158
+ hidden_states = flex_attention_func(query, key, value, block_mask=block_mask)
159
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
160
+ elif neg_mode:
161
+ # Fallback to original implementation if flex_attention is not available
162
  res = int(math.sqrt((end_of_hidden_states-(text_seq if encoder_hidden_states is None else 0)) // num))
163
  hw = res*res
164
  mask_ = torch.zeros(1, res, num*res, res, num*res).to(query.device)
 
169
  mask[:, 512:, 512:] = mask_
170
  mask = mask.bool()
171
  mask = rearrange(mask.unsqueeze(0).expand(attn.heads, -1, -1, -1), "nh b ... -> b nh ...")
172
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False, attn_mask=mask)
173
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
174
+ else:
175
+ # No masking needed
176
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False, attn_mask=None)
177
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
178
 
179
  hidden_states = hidden_states.to(query.dtype)
180
 
181
  if encoder_hidden_states is not None:
182
  encoder_hidden_states, hidden_states = (
183
  hidden_states[:, : encoder_hidden_states.shape[1]],
184
+ hidden_states[:, encoder_hidden_states.shape[1]:],
185
  )
186
  hidden_states = hidden_states[:, :end_of_hidden_states]
187
 
 
247
  image_rotary_emb=None,
248
  joint_attention_kwargs: Optional[Dict[str, Any]] = None,
249
  ):
250
+ dtype = hidden_states.dtype
251
  residual = hidden_states
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
  attn_output = self.attn(
256
+ hidden_states=norm_hidden_states.to(dtype),
257
  image_rotary_emb=image_rotary_emb,
258
  **joint_attention_kwargs,
 
259
  )
260
 
261
  hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
 
317
  image_rotary_emb=None,
318
  joint_attention_kwargs: Optional[Dict[str, Any]] = None
319
  ):
320
+ dtype = hidden_states.dtype
321
  norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
 
322
  norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = (self.norm1_context(encoder_hidden_states, emb=temb))
323
 
324
  # Attention.
325
  attn_output, context_attn_output = self.attn(
326
+ hidden_states=norm_hidden_states.to(dtype),
327
+ encoder_hidden_states=norm_encoder_hidden_states.to(dtype),
328
  image_rotary_emb=image_rotary_emb,
329
  **joint_attention_kwargs,
 
330
  )
331
 
332
  # Process attention outputs for the `hidden_states`.
 
378
  # restore original scaling values after exiting the context
379
  for module, scaling in original_scaling.items():
380
  module.scaling = scaling
381
+
382
+
383
  class FluxTransformer2DModelWithMasking(
384
  ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin
385
  ):
 
493
  fn_recursive_add_processors(name, module, processors)
494
 
495
  return processors
496
+
497
  def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
498
  r"""
499
  Sets the attention processor to use to compute attention.
 
606
  if img_ids.ndim == 3:
607
  img_ids = img_ids[0]
608
 
609
+ ids = torch.cat((txt_ids, img_ids), dim=0).to(hidden_states.dtype)
 
 
610
 
611
  image_rotary_emb = self.pos_embed(ids)
612
 
 
682
  joint_attention_kwargs=joint_attention_kwargs,
683
  )
684
 
685
+ hidden_states = hidden_states[:, encoder_hidden_states.shape[1]:, ...]
686
 
687
  hidden_states = self.norm_out(hidden_states, temb)
688
  output = self.proj_out(hidden_states)