MCPcopy Create free account
hub / github.com/aim-uofa/Framer / IPAdapterAttnProcessor

Class IPAdapterAttnProcessor

models_diffusers/attention_processor.py:1990–2097  ·  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

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

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected