In this repo, is there any usage of attention with dropout?
- User
In this repo, is there any usage of attention with dropout?
Assistant
Yes, there is usage of attention with dropout in this repository.
A clear example can be found in
comfy\ldm\ace\lyric_encoder.pywithin theMultiHeadedAttentionclass. It initializes annn.Dropoutlayer and actively applies it to the attention weights (the result of the softmax) before multiplying with the values:pythonelse: attn = torch.softmax(scores, dim=-1) # (batch, head, time1, time2) p_attn = self.dropout(attn) x = torch.matmul(p_attn, value) # (batch, head, time1, d_k)Additionally, there are a few other related occurrences:
- In
comfy\ldm\modules\attention.py, aCrossAttentionmodule applies dropout to the output of the attention computation:self.to_out = nn.Sequential(..., nn.Dropout(dropout)). - The codebase uses
scaled_dot_product_attention(often mapped totorch.nn.functional.scaled_dot_product_attention) across several files, which accepts adropout_pargument. However, in almost all these calls,dropout_pis explicitly set to0.0. - In
comfy\ldm\pixart\blocks.py,self.attn_drop = nn.Dropout(attn_drop)is initialized inMultiHeadCrossAttention, though it goes unused in its forward pass as it falls back to a customoptimized_attentionfunction without applying the dropout.
- In
- User
FlashAttention 3 does not support dropout. But we only need to support inference, so dropout should work like some static scaling. How to implement it with FlashAttention 3 in comfy/ldm/modules/attention.py ? You may check how it's implemented in C:\flash-attention\ .
Assistant
I have replaced the FlashAttention 2 fallback with standard
flash_attn_func_3and applied the static scaling corresponding to dropout in expectation mode.In PyTorch, applying dropout also multiplies the non-dropped elements by
1.0 / (1.0 - dropout_p). Since FlashAttention 3 does not support a dropout mask natively (and doesn't accept adropout_pargument), but we only need to support inference without stochastic dropping, we can compute the equivalent expected value by statically multiplying the result of FA3 by that same scaling factor.If we check
C:\flash-attention\hopper\test_util.py, this is exactly how they handle the static computation for dropout scale checks:pythondropout_scaling = 1.0 / (1 - dropout_p) # ... output = torch.einsum("bhts,bshd->bthd", attention_drop, v * dropout_scaling)I have successfully updated the wrapper in to: