MCPcopy Create free account
hub / github.com/UVA-Computer-Vision-Lab/FrameINO / AttnProcessor2_0

Class AttnProcessor2_0

architecture/attention_processor.py:3225–3316  ·  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

3223
3224
3225class AttnProcessor2_0:
3226 r"""
3227 Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
3228 """
3229
3230 def __init__(self):
3231 if not hasattr(F, "scaled_dot_product_attention"):
3232 raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
3233
3234 def __call__(
3235 self,
3236 attn: Attention,
3237 hidden_states: torch.Tensor,
3238 encoder_hidden_states: Optional[torch.Tensor] = None,
3239 attention_mask: Optional[torch.Tensor] = None,
3240 temb: Optional[torch.Tensor] = None,
3241 *args,
3242 **kwargs,
3243 ) -> torch.Tensor:
3244 if len(args) > 0 or kwargs.get("scale", None) is not None:
3245 deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
3246 deprecate("scale", "1.0.0", deprecation_message)
3247
3248 residual = hidden_states
3249 if attn.spatial_norm is not None:
3250 hidden_states = attn.spatial_norm(hidden_states, temb)
3251
3252 input_ndim = hidden_states.ndim
3253
3254 if input_ndim == 4:
3255 batch_size, channel, height, width = hidden_states.shape
3256 hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
3257
3258 batch_size, sequence_length, _ = (
3259 hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
3260 )
3261
3262 if attention_mask is not None:
3263 attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
3264 # scaled_dot_product_attention expects attention_mask shape to be
3265 # (batch, heads, source_length, target_length)
3266 attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
3267
3268 if attn.group_norm is not None:
3269 hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
3270
3271 query = attn.to_q(hidden_states)
3272
3273 if encoder_hidden_states is None:
3274 encoder_hidden_states = hidden_states
3275 elif attn.norm_cross:
3276 encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
3277
3278 key = attn.to_k(encoder_hidden_states)
3279 value = attn.to_v(encoder_hidden_states)
3280
3281 inner_dim = key.shape[-1]
3282 head_dim = inner_dim // attn.heads

Calls

no outgoing calls

Tested by

no test coverage detected