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

Class AttnProcessor2_0

models_diffusers/attention_processor.py:1178–1263  ·  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

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

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