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

Class AttnAddedKVProcessor

models_diffusers/attention_processor.py:873–934  ·  view source on GitHub ↗

r""" Processor for performing attention-related computations with extra learnable key and value matrices for the text encoder.

Source from the content-addressed store, hash-verified

871
872
873class AttnAddedKVProcessor:
874 r"""
875 Processor for performing attention-related computations with extra learnable key and value matrices for the text
876 encoder.
877 """
878
879 def __call__(
880 self,
881 attn: Attention,
882 hidden_states: torch.FloatTensor,
883 encoder_hidden_states: Optional[torch.FloatTensor] = None,
884 attention_mask: Optional[torch.FloatTensor] = None,
885 scale: float = 1.0,
886 ) -> torch.Tensor:
887 residual = hidden_states
888
889 args = () if USE_PEFT_BACKEND else (scale,)
890
891 hidden_states = hidden_states.view(hidden_states.shape[0], hidden_states.shape[1], -1).transpose(1, 2)
892 batch_size, sequence_length, _ = hidden_states.shape
893
894 attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
895
896 if encoder_hidden_states is None:
897 encoder_hidden_states = hidden_states
898 elif attn.norm_cross:
899 encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
900
901 hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
902
903 query = attn.to_q(hidden_states, *args)
904 query = attn.head_to_batch_dim(query)
905
906 encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states, *args)
907 encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states, *args)
908 encoder_hidden_states_key_proj = attn.head_to_batch_dim(encoder_hidden_states_key_proj)
909 encoder_hidden_states_value_proj = attn.head_to_batch_dim(encoder_hidden_states_value_proj)
910
911 if not attn.only_cross_attention:
912 key = attn.to_k(hidden_states, *args)
913 value = attn.to_v(hidden_states, *args)
914 key = attn.head_to_batch_dim(key)
915 value = attn.head_to_batch_dim(value)
916 key = torch.cat([encoder_hidden_states_key_proj, key], dim=1)
917 value = torch.cat([encoder_hidden_states_value_proj, value], dim=1)
918 else:
919 key = encoder_hidden_states_key_proj
920 value = encoder_hidden_states_value_proj
921
922 attention_probs = attn.get_attention_scores(query, key, attention_mask)
923 hidden_states = torch.bmm(attention_probs, value)
924 hidden_states = attn.batch_to_head_dim(hidden_states)
925
926 # linear proj
927 hidden_states = attn.to_out[0](hidden_states, *args)
928 # dropout
929 hidden_states = attn.to_out[1](hidden_states)
930

Callers 3

set_attention_sliceMethod · 0.85
__call__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected