MCPcopy Create free account
hub / github.com/Francis-Rings/MotionFollower / XFormersAttnProcessor

Class XFormersAttnProcessor

src/models/attn_process_diffuser.py:1083–1171  ·  view source on GitHub ↗

r""" Processor for implementing memory efficient attention using xFormers. Args: attention_op (`Callable`, *optional*, defaults to `None`): The base [operator](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.AttentionOpBase)

Source from the content-addressed store, hash-verified

1081
1082
1083class XFormersAttnProcessor:
1084 r"""
1085 Processor for implementing memory efficient attention using xFormers.
1086
1087 Args:
1088 attention_op (`Callable`, *optional*, defaults to `None`):
1089 The base
1090 [operator](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.AttentionOpBase) to
1091 use as the attention operator. It is recommended to set to `None`, and allow xFormers to choose the best
1092 operator.
1093 """
1094
1095 def __init__(self, attention_op: Optional[Callable] = None):
1096 self.attention_op = attention_op
1097
1098 def __call__(
1099 self,
1100 attn: Attention,
1101 hidden_states: torch.FloatTensor,
1102 encoder_hidden_states: Optional[torch.FloatTensor] = None,
1103 attention_mask: Optional[torch.FloatTensor] = None,
1104 temb: Optional[torch.FloatTensor] = None,
1105 scale: float = 1.0,
1106 ) -> torch.FloatTensor:
1107 residual = hidden_states
1108
1109 args = () if USE_PEFT_BACKEND else (scale,)
1110
1111 if attn.spatial_norm is not None:
1112 hidden_states = attn.spatial_norm(hidden_states, temb)
1113
1114 input_ndim = hidden_states.ndim
1115
1116 if input_ndim == 4:
1117 batch_size, channel, height, width = hidden_states.shape
1118 hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
1119
1120 batch_size, key_tokens, _ = (
1121 hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
1122 )
1123
1124 attention_mask = attn.prepare_attention_mask(attention_mask, key_tokens, batch_size)
1125 if attention_mask is not None:
1126 # expand our mask's singleton query_tokens dimension:
1127 # [batch*heads, 1, key_tokens] ->
1128 # [batch*heads, query_tokens, key_tokens]
1129 # so that it can be added as a bias onto the attention scores that xformers computes:
1130 # [batch*heads, query_tokens, key_tokens]
1131 # we do this explicitly because xformers doesn't broadcast the singleton dimension for us.
1132 _, query_tokens, _ = hidden_states.shape
1133 attention_mask = attention_mask.expand(-1, query_tokens, -1)
1134
1135 if attn.group_norm is not None:
1136 hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
1137
1138 query = attn.to_q(hidden_states, *args)
1139
1140 if encoder_hidden_states is None:

Callers 2

__call__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected