MCPcopy Create free account
hub / github.com/AlayaLab/Hive / AttnProcessor2_0

Class AttnProcessor2_0

models/flowsep/diffusers/models/attention_processor.py:975–1054  ·  view source on GitHub ↗

r""" Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).

Source from the content-addressed store, hash-verified

973
974
975class AttnProcessor2_0:
976 r"""
977 Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
978 """
979
980 def __init__(self):
981 if not hasattr(F, "scaled_dot_product_attention"):
982 raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
983
984 def __call__(
985 self,
986 attn: Attention,
987 hidden_states,
988 encoder_hidden_states=None,
989 attention_mask=None,
990 temb=None,
991 ):
992 residual = hidden_states
993
994 if attn.spatial_norm is not None:
995 hidden_states = attn.spatial_norm(hidden_states, temb)
996
997 input_ndim = hidden_states.ndim
998
999 if input_ndim == 4:
1000 batch_size, channel, height, width = hidden_states.shape
1001 hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
1002
1003 batch_size, sequence_length, _ = (
1004 hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
1005 )
1006 inner_dim = hidden_states.shape[-1]
1007
1008 if attention_mask is not None:
1009 attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
1010 # scaled_dot_product_attention expects attention_mask shape to be
1011 # (batch, heads, source_length, target_length)
1012 attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
1013
1014 if attn.group_norm is not None:
1015 hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
1016
1017 query = attn.to_q(hidden_states)
1018
1019 if encoder_hidden_states is None:
1020 encoder_hidden_states = hidden_states
1021 elif attn.norm_cross:
1022 encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
1023
1024 key = attn.to_k(encoder_hidden_states)
1025 value = attn.to_v(encoder_hidden_states)
1026
1027 head_dim = inner_dim // attn.heads
1028 query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
1029 key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
1030 value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
1031
1032 # the output of sdp = (batch, num_heads, seq_len, head_dim)

Callers 3

__init__Method · 0.85
set_attention_sliceMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected