r""" Attention processor for ID-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`. scale (`float`, defaults to 1.0): the w
| 76 | |
| 77 | |
| 78 | class IDAttnProcessor(nn.Module): |
| 79 | r""" |
| 80 | Attention processor for ID-Adapater. |
| 81 | Args: |
| 82 | hidden_size (`int`): |
| 83 | The hidden size of the attention layer. |
| 84 | cross_attention_dim (`int`): |
| 85 | The number of channels in the `encoder_hidden_states`. |
| 86 | scale (`float`, defaults to 1.0): |
| 87 | the weight scale of image prompt. |
| 88 | """ |
| 89 | |
| 90 | def __init__(self, hidden_size, cross_attention_dim=None): |
| 91 | super().__init__() |
| 92 | self.id_to_k = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False) |
| 93 | self.id_to_v = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False) |
| 94 | |
| 95 | def __call__( |
| 96 | self, |
| 97 | attn, |
| 98 | hidden_states, |
| 99 | encoder_hidden_states=None, |
| 100 | attention_mask=None, |
| 101 | temb=None, |
| 102 | id_embedding=None, |
| 103 | id_scale=1.0, |
| 104 | ): |
| 105 | residual = hidden_states |
| 106 | |
| 107 | if attn.spatial_norm is not None: |
| 108 | hidden_states = attn.spatial_norm(hidden_states, temb) |
| 109 | |
| 110 | input_ndim = hidden_states.ndim |
| 111 | |
| 112 | if input_ndim == 4: |
| 113 | batch_size, channel, height, width = hidden_states.shape |
| 114 | hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2) |
| 115 | |
| 116 | batch_size, sequence_length, _ = ( |
| 117 | hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape |
| 118 | ) |
| 119 | attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) |
| 120 | |
| 121 | if attn.group_norm is not None: |
| 122 | hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) |
| 123 | |
| 124 | query = attn.to_q(hidden_states) |
| 125 | |
| 126 | if encoder_hidden_states is None: |
| 127 | encoder_hidden_states = hidden_states |
| 128 | elif attn.norm_cross: |
| 129 | encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states) |
| 130 | |
| 131 | key = attn.to_k(encoder_hidden_states) |
| 132 | value = attn.to_v(encoder_hidden_states) |
| 133 | |
| 134 | query = attn.head_to_batch_dim(query) |
| 135 | key = attn.head_to_batch_dim(key) |
no outgoing calls
no test coverage detected