(
self,
attn: Attention,
hidden_states: torch.Tensor,
encoder_hidden_states: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
temb: Optional[torch.Tensor] = None,
scale: float = 1.0,
)
| 109 | self.default_processor = AttnProcessor() |
| 110 | |
| 111 | def __call__( |
| 112 | self, |
| 113 | attn: Attention, |
| 114 | hidden_states: torch.Tensor, |
| 115 | encoder_hidden_states: Optional[torch.Tensor] = None, |
| 116 | attention_mask: Optional[torch.Tensor] = None, |
| 117 | temb: Optional[torch.Tensor] = None, |
| 118 | scale: float = 1.0, |
| 119 | ) -> torch.Tensor: |
| 120 | # Automatically recognize the resolution of the current attention layer and resize the masks accordingly |
| 121 | downscale_factor = self.mask_resoltuion // hidden_states.shape[1] |
| 122 | |
| 123 | mask = None |
| 124 | for factor in self.scale_factors: |
| 125 | if downscale_factor == factor**2: |
| 126 | shape = (self.shape[0] // factor, self.shape[1] // factor) |
| 127 | mask = F.interpolate(self.mask, shape, mode="bicubic") # B, 1, H, W |
| 128 | break |
| 129 | if mask is None: |
| 130 | return self.default_processor(attn, hidden_states, encoder_hidden_states, attention_mask, temb, scale) |
| 131 | |
| 132 | # STARTS HERE |
| 133 | residual = hidden_states |
| 134 | # Save the input hidden_states for later use |
| 135 | input_hidden_states = hidden_states |
| 136 | |
| 137 | # ================================================== # |
| 138 | # =============== SELF ATTENTION 1 ================= # |
| 139 | # ================================================== # |
| 140 | |
| 141 | if attn.spatial_norm is not None: |
| 142 | hidden_states = attn.spatial_norm(hidden_states, temb) |
| 143 | |
| 144 | input_ndim = hidden_states.ndim |
| 145 | |
| 146 | if input_ndim == 4: |
| 147 | batch_size, channel, height, width = hidden_states.shape |
| 148 | hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2) |
| 149 | |
| 150 | batch_size, sequence_length, _ = ( |
| 151 | hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape |
| 152 | ) |
| 153 | attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) |
| 154 | |
| 155 | if attn.group_norm is not None: |
| 156 | hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) |
| 157 | |
| 158 | query = attn.to_q(hidden_states) |
| 159 | |
| 160 | if encoder_hidden_states is None: |
| 161 | encoder_hidden_states = hidden_states |
| 162 | elif attn.norm_cross: |
| 163 | encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states) |
| 164 | |
| 165 | key = attn.to_k(encoder_hidden_states) |
| 166 | value = attn.to_v(encoder_hidden_states) |
| 167 | |
| 168 | query = attn.head_to_batch_dim(query) |
nothing calls this directly
no test coverage detected