MCPcopy Create free account
hub / github.com/MatrixTeam-AI/RAIN / XFormersAttnProcessor

Class XFormersAttnProcessor

src/models/attention_processor.py:1075–1177  ·  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) to

Source from the content-addressed store, hash-verified

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

Callers 2

__call__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected