66import torch .nn as nn
77from einops import rearrange
88
9- from comfy .ldm .modules .attention import optimized_attention
9+ from comfy .ldm .modules .attention import AttentionTensorContainer , optimized_attention
1010from comfy .ldm .flux .layers import EmbedND
1111from comfy .ldm .flux .math import apply_rope1 , rope
1212import comfy .ldm .common_dit
@@ -81,17 +81,21 @@ def qkv_fn_k(x):
8181 q = qkv_fn_q (x )
8282 k = qkv_fn_k (x )
8383
84+ if patches .get ("attn1_patch" ):
85+ q_patch , k_patch = q , k
86+ q = AttentionTensorContainer (q .view (b , s , n * d ))
87+ k = AttentionTensorContainer (k .view (b , s , n * d ))
88+ v = AttentionTensorContainer (self .v (x ).view (b , s , n * d ))
89+
8490 x = optimized_attention (
85- q .view (b , s , n * d ),
86- k .view (b , s , n * d ),
87- self .v (x ).view (b , s , n * d ),
91+ q , k , v ,
8892 heads = self .num_heads ,
8993 transformer_options = transformer_options ,
9094 )
9195
9296 if "attn1_patch" in patches :
9397 for p in patches ["attn1_patch" ]:
94- x = p ({"x" : x , "q" : q , "k" : k , "transformer_options" : transformer_options })
98+ x = p ({"x" : x , "q" : q_patch , "k" : k_patch , "transformer_options" : transformer_options })
9599
96100 x = self .o (x )
97101 return x
@@ -106,9 +110,9 @@ def forward(self, x, context, transformer_options={}, **kwargs):
106110 context(Tensor): Shape [B, L2, C]
107111 """
108112 # compute query, key, value
109- q = self .norm_q (self .q (x ))
110- k = self .norm_k (self .k (context ))
111- v = self .v (context )
113+ q = AttentionTensorContainer ( self .norm_q (self .q (x ) ))
114+ k = AttentionTensorContainer ( self .norm_k (self .k (context ) ))
115+ v = AttentionTensorContainer ( self .v (context ) )
112116
113117 # compute attention
114118 x = optimized_attention (q , k , v , heads = self .num_heads , transformer_options = transformer_options )
@@ -143,13 +147,15 @@ def forward(self, x, context, context_img_len, transformer_options={}):
143147
144148 # compute query, key, value
145149 q = self .norm_q (self .q (x ))
146- k = self .norm_k (self .k (context ))
147- v = self .v (context )
148150 k_img = self .norm_k_img (self .k_img (context_img ))
149151 v_img = self .v_img (context_img )
150152 # Sageattn can cause Nans here, don't allow it as there is no speed difference anyway as img attention is tiny.
151153 img_x = optimized_attention (q , k_img , v_img , heads = self .num_heads , transformer_options = transformer_options , low_precision_attention = False )
154+ del k_img , v_img
152155 # compute attention
156+ q = AttentionTensorContainer (q )
157+ k = AttentionTensorContainer (self .norm_k (self .k (context )))
158+ v = AttentionTensorContainer (self .v (context ))
153159 x = optimized_attention (q , k , v , heads = self .num_heads , transformer_options = transformer_options )
154160
155161 # output
0 commit comments