r""" Processor for performing attention-related computations with extra learnable key and value matrices for the text encoder.
| 873 | |
| 874 | |
| 875 | class AttnAddedKVProcessor: |
| 876 | r""" |
| 877 | Processor for performing attention-related computations with extra learnable key and value matrices for the text |
| 878 | encoder. |
| 879 | """ |
| 880 | |
| 881 | def __call__( |
| 882 | self, |
| 883 | attn: Attention, |
| 884 | hidden_states: torch.FloatTensor, |
| 885 | encoder_hidden_states: Optional[torch.FloatTensor] = None, |
| 886 | attention_mask: Optional[torch.FloatTensor] = None, |
| 887 | scale: float = 1.0, |
| 888 | ) -> torch.Tensor: |
| 889 | residual = hidden_states |
| 890 | |
| 891 | args = () if USE_PEFT_BACKEND else (scale,) |
| 892 | |
| 893 | hidden_states = hidden_states.view(hidden_states.shape[0], hidden_states.shape[1], -1).transpose(1, 2) |
| 894 | batch_size, sequence_length, _ = hidden_states.shape |
| 895 | |
| 896 | attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) |
| 897 | |
| 898 | if encoder_hidden_states is None: |
| 899 | encoder_hidden_states = hidden_states |
| 900 | elif attn.norm_cross: |
| 901 | encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states) |
| 902 | |
| 903 | hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) |
| 904 | |
| 905 | query = attn.to_q(hidden_states, *args) |
| 906 | query = attn.head_to_batch_dim(query) |
| 907 | |
| 908 | encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states, *args) |
| 909 | encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states, *args) |
| 910 | encoder_hidden_states_key_proj = attn.head_to_batch_dim(encoder_hidden_states_key_proj) |
| 911 | encoder_hidden_states_value_proj = attn.head_to_batch_dim(encoder_hidden_states_value_proj) |
| 912 | |
| 913 | if not attn.only_cross_attention: |
| 914 | key = attn.to_k(hidden_states, *args) |
| 915 | value = attn.to_v(hidden_states, *args) |
| 916 | key = attn.head_to_batch_dim(key) |
| 917 | value = attn.head_to_batch_dim(value) |
| 918 | key = torch.cat([encoder_hidden_states_key_proj, key], dim=1) |
| 919 | value = torch.cat([encoder_hidden_states_value_proj, value], dim=1) |
| 920 | else: |
| 921 | key = encoder_hidden_states_key_proj |
| 922 | value = encoder_hidden_states_value_proj |
| 923 | |
| 924 | attention_probs = attn.get_attention_scores(query, key, attention_mask) |
| 925 | hidden_states = torch.bmm(attention_probs, value) |
| 926 | hidden_states = attn.batch_to_head_dim(hidden_states) |
| 927 | |
| 928 | # linear proj |
| 929 | hidden_states = attn.to_out[0](hidden_states, *args) |
| 930 | # dropout |
| 931 | hidden_states = attn.to_out[1](hidden_states) |
| 932 |
no outgoing calls
no test coverage detected