MCPcopy Create free account
hub / github.com/aim-uofa/Framer / AttnProcessor

Class AttnProcessor

models_diffusers/attention_processor.py:694–766  ·  view source on GitHub ↗

r""" Default processor for performing attention-related computations.

Source from the content-addressed store, hash-verified

692
693
694class AttnProcessor:
695 r"""
696 Default processor for performing attention-related computations.
697 """
698
699 def __call__(
700 self,
701 attn: Attention,
702 hidden_states: torch.FloatTensor,
703 encoder_hidden_states: Optional[torch.FloatTensor] = None,
704 attention_mask: Optional[torch.FloatTensor] = None,
705 temb: Optional[torch.FloatTensor] = None,
706 scale: float = 1.0,
707 ) -> torch.Tensor:
708 residual = hidden_states
709
710 args = () if USE_PEFT_BACKEND else (scale,)
711
712 if attn.spatial_norm is not None:
713 hidden_states = attn.spatial_norm(hidden_states, temb)
714
715 input_ndim = hidden_states.ndim
716
717 if input_ndim == 4:
718 batch_size, channel, height, width = hidden_states.shape
719 hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
720
721 batch_size, sequence_length, _ = (
722 hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
723 )
724 attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
725
726 if attn.group_norm is not None:
727 hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
728
729 query = attn.to_q(hidden_states, *args)
730
731 if encoder_hidden_states is None:
732 encoder_hidden_states = hidden_states
733 elif attn.norm_cross:
734 encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
735
736 key = attn.to_k(encoder_hidden_states, *args)
737 value = attn.to_v(encoder_hidden_states, *args)
738
739 # Record the Q,K,V for PCA guidance
740 self.key = key
741 # self.query = query
742 # self.value = value
743 self.hidden_state = hidden_states.detach()
744
745 query = attn.head_to_batch_dim(query)
746 key = attn.head_to_batch_dim(key)
747 value = attn.head_to_batch_dim(value)
748
749 attention_probs = attn.get_attention_scores(query, key, attention_mask)
750 hidden_states = torch.bmm(attention_probs, value)
751 hidden_states = attn.batch_to_head_dim(hidden_states)

Callers 6

__init__Method · 0.85
set_attention_sliceMethod · 0.85
__call__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected