MCPcopy Create free account
hub / github.com/MatrixTeam-AI/RAIN / IPAdapterAttnProcessor

Class IPAdapterAttnProcessor

src/models/attention_processor.py:1992–2099  ·  view source on GitHub ↗

r""" Attention processor for IP-Adapater. 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): The

Source from the content-addressed store, hash-verified

1990
1991
1992class IPAdapterAttnProcessor(nn.Module):
1993 r"""
1994 Attention processor for IP-Adapater.
1995
1996 Args:
1997 hidden_size (`int`):
1998 The hidden size of the attention layer.
1999 cross_attention_dim (`int`):
2000 The number of channels in the `encoder_hidden_states`.
2001 num_tokens (`int`, defaults to 4):
2002 The context length of the image features.
2003 scale (`float`, defaults to 1.0):
2004 the weight scale of image prompt.
2005 """
2006
2007 def __init__(self, hidden_size, cross_attention_dim=None, num_tokens=4, scale=1.0):
2008 super().__init__()
2009
2010 self.hidden_size = hidden_size
2011 self.cross_attention_dim = cross_attention_dim
2012 self.num_tokens = num_tokens
2013 self.scale = scale
2014
2015 self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
2016 self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
2017
2018 def __call__(
2019 self,
2020 attn,
2021 hidden_states,
2022 encoder_hidden_states=None,
2023 attention_mask=None,
2024 temb=None,
2025 scale=1.0,
2026 ):
2027 if scale != 1.0:
2028 logger.warning("`scale` of IPAttnProcessor should be set with `set_ip_adapter_scale`.")
2029 residual = hidden_states
2030
2031 if attn.spatial_norm is not None:
2032 hidden_states = attn.spatial_norm(hidden_states, temb)
2033
2034 input_ndim = hidden_states.ndim
2035
2036 if input_ndim == 4:
2037 batch_size, channel, height, width = hidden_states.shape
2038 hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
2039
2040 batch_size, sequence_length, _ = (
2041 hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
2042 )
2043 attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
2044
2045 if attn.group_norm is not None:
2046 hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
2047
2048 query = attn.to_q(hidden_states)
2049

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected