r""" Default processor for performing attention-related computations.
| 713 | |
| 714 | |
| 715 | class AttnProcessor: |
| 716 | r""" |
| 717 | Default processor for performing attention-related computations. |
| 718 | """ |
| 719 | |
| 720 | def __call__( |
| 721 | self, |
| 722 | attn: Attention, |
| 723 | hidden_states: torch.Tensor, |
| 724 | encoder_hidden_states: Optional[torch.Tensor] = None, |
| 725 | attention_mask: Optional[torch.Tensor] = None, |
| 726 | temb: Optional[torch.Tensor] = None, |
| 727 | *args, |
| 728 | **kwargs, |
| 729 | ) -> torch.Tensor: |
| 730 | if len(args) > 0 or kwargs.get("scale", None) is not None: |
| 731 | deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`." |
| 732 | deprecate("scale", "1.0.0", deprecation_message) |
| 733 | |
| 734 | residual = hidden_states |
| 735 | |
| 736 | if attn.spatial_norm is not None: |
| 737 | hidden_states = attn.spatial_norm(hidden_states, temb) |
| 738 | |
| 739 | input_ndim = hidden_states.ndim |
| 740 | |
| 741 | if input_ndim == 4: |
| 742 | batch_size, channel, height, width = hidden_states.shape |
| 743 | hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2) |
| 744 | |
| 745 | batch_size, sequence_length, _ = ( |
| 746 | hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape |
| 747 | ) |
| 748 | attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) |
| 749 | |
| 750 | if attn.group_norm is not None: |
| 751 | hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) |
| 752 | |
| 753 | query = attn.to_q(hidden_states) |
| 754 | |
| 755 | if encoder_hidden_states is None: |
| 756 | encoder_hidden_states = hidden_states |
| 757 | elif attn.norm_cross: |
| 758 | encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states) |
| 759 | |
| 760 | key = attn.to_k(encoder_hidden_states) |
| 761 | value = attn.to_v(encoder_hidden_states) |
| 762 | |
| 763 | query = attn.head_to_batch_dim(query) |
| 764 | key = attn.head_to_batch_dim(key) |
| 765 | value = attn.head_to_batch_dim(value) |
| 766 | |
| 767 | attention_probs = attn.get_attention_scores(query, key, attention_mask) |
| 768 | hidden_states = torch.bmm(attention_probs, value) |
| 769 | hidden_states = attn.batch_to_head_dim(hidden_states) |
| 770 | |
| 771 | # linear proj |
| 772 | hidden_states = attn.to_out[0](hidden_states) |
no outgoing calls