MCPcopy Create free account
hub / github.com/YesianRohn/TextSSR / AttnProcessor2_0

Class AttnProcessor2_0

diffusers/src/diffusers/models/attention_processor.py:2296–2387  ·  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

2294
2295
2296class AttnProcessor2_0:
2297 r"""
2298 Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
2299 """
2300
2301 def __init__(self):
2302 if not hasattr(F, "scaled_dot_product_attention"):
2303 raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
2304
2305 def __call__(
2306 self,
2307 attn: Attention,
2308 hidden_states: torch.Tensor,
2309 encoder_hidden_states: Optional[torch.Tensor] = None,
2310 attention_mask: Optional[torch.Tensor] = None,
2311 temb: Optional[torch.Tensor] = None,
2312 *args,
2313 **kwargs,
2314 ) -> torch.Tensor:
2315 if len(args) > 0 or kwargs.get("scale", None) is not None:
2316 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`."
2317 deprecate("scale", "1.0.0", deprecation_message)
2318
2319 residual = hidden_states
2320 if attn.spatial_norm is not None:
2321 hidden_states = attn.spatial_norm(hidden_states, temb)
2322
2323 input_ndim = hidden_states.ndim
2324
2325 if input_ndim == 4:
2326 batch_size, channel, height, width = hidden_states.shape
2327 hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
2328
2329 batch_size, sequence_length, _ = (
2330 hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
2331 )
2332
2333 if attention_mask is not None:
2334 attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
2335 # scaled_dot_product_attention expects attention_mask shape to be
2336 # (batch, heads, source_length, target_length)
2337 attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
2338
2339 if attn.group_norm is not None:
2340 hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
2341
2342 query = attn.to_q(hidden_states)
2343
2344 if encoder_hidden_states is None:
2345 encoder_hidden_states = hidden_states
2346 elif attn.norm_cross:
2347 encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
2348
2349 key = attn.to_k(encoder_hidden_states)
2350 value = attn.to_v(encoder_hidden_states)
2351
2352 inner_dim = key.shape[-1]
2353 head_dim = inner_dim // attn.heads

Calls

no outgoing calls