r""" Processor for performing attention-related computations with extra learnable key and value matrices for the text encoder.
| 692 | |
| 693 | |
| 694 | class AttnAddedKVProcessor: |
| 695 | r""" |
| 696 | Processor for performing attention-related computations with extra learnable key and value matrices for the text |
| 697 | encoder. |
| 698 | """ |
| 699 | |
| 700 | def __call__(self, attn: Attention, hidden_states, encoder_hidden_states=None, attention_mask=None): |
| 701 | residual = hidden_states |
| 702 | hidden_states = hidden_states.view(hidden_states.shape[0], hidden_states.shape[1], -1).transpose(1, 2) |
| 703 | batch_size, sequence_length, _ = hidden_states.shape |
| 704 | |
| 705 | attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) |
| 706 | |
| 707 | if encoder_hidden_states is None: |
| 708 | encoder_hidden_states = hidden_states |
| 709 | elif attn.norm_cross: |
| 710 | encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states) |
| 711 | |
| 712 | hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) |
| 713 | |
| 714 | query = attn.to_q(hidden_states) |
| 715 | query = attn.head_to_batch_dim(query) |
| 716 | |
| 717 | encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states) |
| 718 | encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states) |
| 719 | encoder_hidden_states_key_proj = attn.head_to_batch_dim(encoder_hidden_states_key_proj) |
| 720 | encoder_hidden_states_value_proj = attn.head_to_batch_dim(encoder_hidden_states_value_proj) |
| 721 | |
| 722 | if not attn.only_cross_attention: |
| 723 | key = attn.to_k(hidden_states) |
| 724 | value = attn.to_v(hidden_states) |
| 725 | key = attn.head_to_batch_dim(key) |
| 726 | value = attn.head_to_batch_dim(value) |
| 727 | key = torch.cat([encoder_hidden_states_key_proj, key], dim=1) |
| 728 | value = torch.cat([encoder_hidden_states_value_proj, value], dim=1) |
| 729 | else: |
| 730 | key = encoder_hidden_states_key_proj |
| 731 | value = encoder_hidden_states_value_proj |
| 732 | |
| 733 | attention_probs = attn.get_attention_scores(query, key, attention_mask) |
| 734 | hidden_states = torch.bmm(attention_probs, value) |
| 735 | hidden_states = attn.batch_to_head_dim(hidden_states) |
| 736 | |
| 737 | # linear proj |
| 738 | hidden_states = attn.to_out[0](hidden_states) |
| 739 | # dropout |
| 740 | hidden_states = attn.to_out[1](hidden_states) |
| 741 | |
| 742 | hidden_states = hidden_states.transpose(-1, -2).reshape(residual.shape) |
| 743 | hidden_states = hidden_states + residual |
| 744 | |
| 745 | return hidden_states |
| 746 | |
| 747 | |
| 748 | class AttnAddedKVProcessor2_0: |
no outgoing calls
no test coverage detected