|
| 1 | +from diffusers.models.attention_processor import Attention |
| 2 | +import torch |
| 3 | +from typing import Optional |
| 4 | +import torch as nn |
| 5 | +from diffusers.models.attention_processor import JointAttnProcessor2_0 |
| 6 | + |
| 7 | +class QEffAttention(Attention): |
| 8 | + |
| 9 | + def __qeff_init__(self): |
| 10 | + processor=QEffJointAttnProcessor2_0() |
| 11 | + self.processor=processor |
| 12 | + processor.query_block_size = 64 |
| 13 | + |
| 14 | + def get_attention_scores( |
| 15 | + self, query: torch.Tensor, key: torch.Tensor, attention_mask: Optional[torch.Tensor] = None |
| 16 | + ) -> torch.Tensor: |
| 17 | + dtype = query.dtype |
| 18 | + if self.upcast_attention: |
| 19 | + query = query.float() |
| 20 | + key = key.float() |
| 21 | + |
| 22 | + if attention_mask is None: |
| 23 | + baddbmm_input = torch.empty( |
| 24 | + query.shape[0], query.shape[1], key.shape[2], dtype=query.dtype, device=query.device |
| 25 | + ) |
| 26 | + beta = 0 |
| 27 | + else: |
| 28 | + baddbmm_input = attention_mask |
| 29 | + beta = 1 |
| 30 | + |
| 31 | + attention_scores = torch.baddbmm( |
| 32 | + baddbmm_input, |
| 33 | + query, |
| 34 | + key, |
| 35 | + beta=beta, |
| 36 | + alpha=self.scale, |
| 37 | + ) |
| 38 | + del baddbmm_input |
| 39 | + |
| 40 | + if self.upcast_softmax: |
| 41 | + attention_scores = attention_scores.float() |
| 42 | + |
| 43 | + attention_probs = attention_scores.softmax(dim=-1) |
| 44 | + del attention_scores |
| 45 | + |
| 46 | + attention_probs = attention_probs.to(dtype) |
| 47 | + |
| 48 | + return attention_probs |
| 49 | + |
| 50 | +class QEffJointAttnProcessor2_0(JointAttnProcessor2_0): |
| 51 | + |
| 52 | + def __call__( |
| 53 | + self, |
| 54 | + attn: QEffAttention, |
| 55 | + hidden_states: torch.FloatTensor, |
| 56 | + encoder_hidden_states: torch.FloatTensor = None, |
| 57 | + attention_mask: Optional[torch.FloatTensor] = None, |
| 58 | + *args, |
| 59 | + **kwargs, |
| 60 | + ) -> torch.FloatTensor: |
| 61 | + residual = hidden_states |
| 62 | + |
| 63 | + batch_size = hidden_states.shape[0] |
| 64 | + |
| 65 | + # `sample` projections. |
| 66 | + query = attn.to_q(hidden_states) |
| 67 | + key = attn.to_k(hidden_states) |
| 68 | + value = attn.to_v(hidden_states) |
| 69 | + |
| 70 | + inner_dim = key.shape[-1] |
| 71 | + head_dim = inner_dim // attn.heads |
| 72 | + |
| 73 | + query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) |
| 74 | + key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) |
| 75 | + value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) |
| 76 | + |
| 77 | + if attn.norm_q is not None: |
| 78 | + query = attn.norm_q(query) |
| 79 | + if attn.norm_k is not None: |
| 80 | + key = attn.norm_k(key) |
| 81 | + |
| 82 | + # `context` projections. |
| 83 | + if encoder_hidden_states is not None: |
| 84 | + encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states) |
| 85 | + encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states) |
| 86 | + encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states) |
| 87 | + |
| 88 | + encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view( |
| 89 | + batch_size, -1, attn.heads, head_dim |
| 90 | + ).transpose(1, 2) |
| 91 | + encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view( |
| 92 | + batch_size, -1, attn.heads, head_dim |
| 93 | + ).transpose(1, 2) |
| 94 | + encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view( |
| 95 | + batch_size, -1, attn.heads, head_dim |
| 96 | + ).transpose(1, 2) |
| 97 | + |
| 98 | + if attn.norm_added_q is not None: |
| 99 | + encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj) |
| 100 | + if attn.norm_added_k is not None: |
| 101 | + encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj) |
| 102 | + |
| 103 | + query = torch.cat([query, encoder_hidden_states_query_proj], dim=2) |
| 104 | + key = torch.cat([key, encoder_hidden_states_key_proj], dim=2) |
| 105 | + value = torch.cat([value, encoder_hidden_states_value_proj], dim=2) |
| 106 | + |
| 107 | + query = query.reshape(-1, query.shape[-2], query.shape[-1]) |
| 108 | + key = key.reshape(-1, key.shape[-2], key.shape[-1]) |
| 109 | + value = value.reshape(-1, value.shape[-2], value.shape[-1]) |
| 110 | + |
| 111 | + # pre-transpose the key |
| 112 | + key = key.transpose(-1, -2) |
| 113 | + if query.size(-2) != value.size(-2): # cross-attention, use regular attention |
| 114 | + # QKV done in single block |
| 115 | + attention_probs = attn.get_attention_scores(query, key, attention_mask) |
| 116 | + hidden_states = torch.bmm(attention_probs, value) |
| 117 | + else: # self-attention, use blocked attention |
| 118 | + # QKV done with block-attention (a la FlashAttentionV2) |
| 119 | + print(f"{query.shape = }, {key.shape = }, {value.shape = }") |
| 120 | + query_block_size = self.query_block_size |
| 121 | + query_seq_len = query.size(-2) |
| 122 | + num_blocks = (query_seq_len + query_block_size - 1) // query_block_size |
| 123 | + for qidx in range(num_blocks): |
| 124 | + query_block = query[:,qidx*query_block_size:(qidx+1)*query_block_size,:] |
| 125 | + attention_probs = attn.get_attention_scores(query_block, key, attention_mask) |
| 126 | + hidden_states_block = torch.bmm(attention_probs, value) |
| 127 | + if qidx == 0: |
| 128 | + hidden_states = hidden_states_block |
| 129 | + else: |
| 130 | + hidden_states = torch.cat((hidden_states, hidden_states_block), -2) |
| 131 | + hidden_states = attn.batch_to_head_dim(hidden_states) |
| 132 | + |
| 133 | + if encoder_hidden_states is not None: |
| 134 | + # Split the attention outputs. |
| 135 | + hidden_states, encoder_hidden_states = ( |
| 136 | + hidden_states[:, : residual.shape[1]], |
| 137 | + hidden_states[:, residual.shape[1] :], |
| 138 | + ) |
| 139 | + if not attn.context_pre_only: |
| 140 | + encoder_hidden_states = attn.to_add_out(encoder_hidden_states) |
| 141 | + |
| 142 | + # linear proj |
| 143 | + hidden_states = attn.to_out[0](hidden_states) |
| 144 | + # dropout |
| 145 | + hidden_states = attn.to_out[1](hidden_states) |
| 146 | + |
| 147 | + if encoder_hidden_states is not None: |
| 148 | + return hidden_states, encoder_hidden_states |
| 149 | + else: |
| 150 | + return hidden_states |
0 commit comments