r""" Default processor for performing attention-related computations.
| 730 | |
| 731 | |
| 732 | class AttnProcessor: |
| 733 | r""" |
| 734 | Default processor for performing attention-related computations. |
| 735 | """ |
| 736 | |
| 737 | def __call__( |
| 738 | self, |
| 739 | attn: Attention, |
| 740 | hidden_states: torch.FloatTensor, |
| 741 | encoder_hidden_states: Optional[torch.FloatTensor] = None, |
| 742 | attention_mask: Optional[torch.FloatTensor] = None, |
| 743 | temb: Optional[torch.FloatTensor] = None, |
| 744 | scale: float = 1.0, |
| 745 | ) -> torch.Tensor: |
| 746 | residual = hidden_states |
| 747 | |
| 748 | args = () if USE_PEFT_BACKEND else (scale,) |
| 749 | |
| 750 | if attn.spatial_norm is not None: |
| 751 | hidden_states = attn.spatial_norm(hidden_states, temb) |
| 752 | |
| 753 | input_ndim = hidden_states.ndim |
| 754 | |
| 755 | if input_ndim == 4: |
| 756 | batch_size, channel, height, width = hidden_states.shape |
| 757 | hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2) |
| 758 | |
| 759 | batch_size, sequence_length, _ = ( |
| 760 | hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape |
| 761 | ) |
| 762 | attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) |
| 763 | |
| 764 | if attn.group_norm is not None: |
| 765 | hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) |
| 766 | |
| 767 | query = attn.to_q(hidden_states, *args) |
| 768 | |
| 769 | if encoder_hidden_states is None: |
| 770 | encoder_hidden_states = hidden_states |
| 771 | elif attn.norm_cross: |
| 772 | encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states) |
| 773 | |
| 774 | key = attn.to_k(encoder_hidden_states, *args) |
| 775 | value = attn.to_v(encoder_hidden_states, *args) |
| 776 | |
| 777 | query = attn.head_to_batch_dim(query) |
| 778 | key = attn.head_to_batch_dim(key) |
| 779 | value = attn.head_to_batch_dim(value) |
| 780 | |
| 781 | attention_probs = attn.get_attention_scores(query, key, attention_mask) |
| 782 | hidden_states = torch.bmm(attention_probs, value) |
| 783 | hidden_states = attn.batch_to_head_dim(hidden_states) |
| 784 | |
| 785 | # linear proj |
| 786 | hidden_states = attn.to_out[0](hidden_states, *args) |
| 787 | # dropout |
| 788 | hidden_states = attn.to_out[1](hidden_states) |
| 789 |
no outgoing calls