MCPcopy Index your code
hub / github.com/huggingface/diffusers / AttnProcessor2_0

Class AttnProcessor2_0

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

2694
2695
2696class AttnProcessor2_0:
2697 r"""
2698 Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
2699 """
2700
2701 def __init__(self):
2702 if not hasattr(F, "scaled_dot_product_attention"):
2703 raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
2704
2705 def __call__(
2706 self,
2707 attn: Attention,
2708 hidden_states: torch.Tensor,
2709 encoder_hidden_states: torch.Tensor | None = None,
2710 attention_mask: torch.Tensor | None = None,
2711 temb: torch.Tensor | None = None,
2712 *args,
2713 **kwargs,
2714 ) -> torch.Tensor:
2715 if len(args) > 0 or kwargs.get("scale", None) is not None:
2716 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`."
2717 deprecate("scale", "1.0.0", deprecation_message)
2718
2719 residual = hidden_states
2720 if attn.spatial_norm is not None:
2721 hidden_states = attn.spatial_norm(hidden_states, temb)
2722
2723 input_ndim = hidden_states.ndim
2724
2725 if input_ndim == 4:
2726 batch_size, channel, height, width = hidden_states.shape
2727 hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
2728
2729 batch_size, sequence_length, _ = (
2730 hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
2731 )
2732
2733 if attention_mask is not None:
2734 attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
2735 # scaled_dot_product_attention expects attention_mask shape to be
2736 # (batch, heads, source_length, target_length)
2737 attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
2738
2739 if attn.group_norm is not None:
2740 hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
2741
2742 query = attn.to_q(hidden_states)
2743
2744 if encoder_hidden_states is None:
2745 encoder_hidden_states = hidden_states
2746 elif attn.norm_cross:
2747 encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
2748
2749 key = attn.to_k(encoder_hidden_states)
2750 value = attn.to_v(encoder_hidden_states)
2751
2752 inner_dim = key.shape[-1]
2753 head_dim = inner_dim // attn.heads

Calls

no outgoing calls

Used in the wild real call sites across dependent graphs

searching dependent graphs…