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

Class AttnProcessor2_0

src/models/attn_process_diffuser.py:1174–1259  ·  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

1172
1173
1174class AttnProcessor2_0:
1175 r"""
1176 Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
1177 """
1178
1179 def __init__(self):
1180 if not hasattr(F, "scaled_dot_product_attention"):
1181 raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
1182
1183 def __call__(
1184 self,
1185 attn: Attention,
1186 hidden_states: torch.FloatTensor,
1187 encoder_hidden_states: Optional[torch.FloatTensor] = None,
1188 attention_mask: Optional[torch.FloatTensor] = None,
1189 temb: Optional[torch.FloatTensor] = None,
1190 scale: float = 1.0,
1191 ) -> torch.FloatTensor:
1192 residual = hidden_states
1193
1194 args = () if USE_PEFT_BACKEND else (scale,)
1195
1196 if attn.spatial_norm is not None:
1197 hidden_states = attn.spatial_norm(hidden_states, temb)
1198
1199 input_ndim = hidden_states.ndim
1200
1201 if input_ndim == 4:
1202 batch_size, channel, height, width = hidden_states.shape
1203 hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
1204
1205 batch_size, sequence_length, _ = (
1206 hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
1207 )
1208
1209 if attention_mask is not None:
1210 attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
1211 # scaled_dot_product_attention expects attention_mask shape to be
1212 # (batch, heads, source_length, target_length)
1213 attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
1214
1215 if attn.group_norm is not None:
1216 hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
1217
1218 args = () if USE_PEFT_BACKEND else (scale,)
1219 query = attn.to_q(hidden_states, *args)
1220
1221 if encoder_hidden_states is None:
1222 encoder_hidden_states = hidden_states
1223 elif attn.norm_cross:
1224 encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
1225
1226 key = attn.to_k(encoder_hidden_states, *args)
1227 value = attn.to_v(encoder_hidden_states, *args)
1228
1229 inner_dim = key.shape[-1]
1230 head_dim = inner_dim // attn.heads
1231

Callers 4

__init__Method · 0.85
set_attention_sliceMethod · 0.85
__call__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected