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

Class IPAdapterAttnProcessor2_0

src/models/attn_process_diffuser.py:2096–2227  ·  view source on GitHub ↗

r""" Attention processor for IP-Adapater for PyTorch 2.0. Args: hidden_size (`int`): The hidden size of the attention layer. cross_attention_dim (`int`): The number of channels in the `encoder_hidden_states`. num_tokens (`int`, default

Source from the content-addressed store, hash-verified

2094
2095
2096class IPAdapterAttnProcessor2_0(torch.nn.Module):
2097 r"""
2098 Attention processor for IP-Adapater for PyTorch 2.0.
2099
2100 Args:
2101 hidden_size (`int`):
2102 The hidden size of the attention layer.
2103 cross_attention_dim (`int`):
2104 The number of channels in the `encoder_hidden_states`.
2105 num_tokens (`int`, defaults to 4):
2106 The context length of the image features.
2107 scale (`float`, defaults to 1.0):
2108 the weight scale of image prompt.
2109 """
2110
2111 def __init__(self, hidden_size, cross_attention_dim=None, num_tokens=4, scale=1.0):
2112 super().__init__()
2113
2114 if not hasattr(F, "scaled_dot_product_attention"):
2115 raise ImportError(
2116 f"{self.__class__.__name__} requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
2117 )
2118
2119 self.hidden_size = hidden_size
2120 self.cross_attention_dim = cross_attention_dim
2121 self.num_tokens = num_tokens
2122 self.scale = scale
2123
2124 self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
2125 self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
2126
2127 def __call__(
2128 self,
2129 attn,
2130 hidden_states,
2131 encoder_hidden_states=None,
2132 attention_mask=None,
2133 temb=None,
2134 scale=1.0,
2135 ):
2136 if scale != 1.0:
2137 logger.warning("`scale` of IPAttnProcessor should be set by `set_ip_adapter_scale`.")
2138 residual = hidden_states
2139
2140 if attn.spatial_norm is not None:
2141 hidden_states = attn.spatial_norm(hidden_states, temb)
2142
2143 input_ndim = hidden_states.ndim
2144
2145 if input_ndim == 4:
2146 batch_size, channel, height, width = hidden_states.shape
2147 hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
2148
2149 batch_size, sequence_length, _ = (
2150 hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
2151 )
2152
2153 if attention_mask is not None:

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected