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