r""" Default processor for performing attention-related computations.
| 700 | |
| 701 | |
| 702 | class AttnProcessor: |
| 703 | r""" |
| 704 | Default processor for performing attention-related computations. |
| 705 | """ |
| 706 | |
| 707 | def __call__( |
| 708 | self, |
| 709 | attn: Attention, |
| 710 | hidden_states: torch.FloatTensor, |
| 711 | encoder_hidden_states: Optional[torch.FloatTensor] = None, |
| 712 | attention_mask: Optional[torch.FloatTensor] = None, |
| 713 | temb: Optional[torch.FloatTensor] = None, |
| 714 | scale: float = 1.0, |
| 715 | ) -> torch.Tensor: |
| 716 | residual = hidden_states |
| 717 | |
| 718 | args = () if USE_PEFT_BACKEND else (scale,) |
| 719 | |
| 720 | if attn.spatial_norm is not None: |
| 721 | hidden_states = attn.spatial_norm(hidden_states, temb) |
| 722 | |
| 723 | input_ndim = hidden_states.ndim |
| 724 | |
| 725 | if input_ndim == 4: |
| 726 | batch_size, channel, height, width = hidden_states.shape |
| 727 | hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2) |
| 728 | |
| 729 | batch_size, sequence_length, _ = ( |
| 730 | hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape |
| 731 | ) |
| 732 | attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) |
| 733 | |
| 734 | if attn.group_norm is not None: |
| 735 | hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) |
| 736 | |
| 737 | query = attn.to_q(hidden_states, *args) |
| 738 | |
| 739 | if encoder_hidden_states is None: |
| 740 | encoder_hidden_states = hidden_states |
| 741 | elif attn.norm_cross: |
| 742 | encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states) |
| 743 | |
| 744 | key = attn.to_k(encoder_hidden_states, *args) |
| 745 | value = attn.to_v(encoder_hidden_states, *args) |
| 746 | |
| 747 | query = attn.head_to_batch_dim(query) |
| 748 | key = attn.head_to_batch_dim(key) |
| 749 | value = attn.head_to_batch_dim(value) |
| 750 | |
| 751 | attention_probs = attn.get_attention_scores(query, key, attention_mask) |
| 752 | hidden_states = torch.bmm(attention_probs, value) |
| 753 | hidden_states = attn.batch_to_head_dim(hidden_states) |
| 754 | |
| 755 | # linear proj |
| 756 | hidden_states = attn.to_out[0](hidden_states, *args) |
| 757 | # dropout |
| 758 | hidden_states = attn.to_out[1](hidden_states) |
| 759 |
no outgoing calls
no test coverage detected