| 275 | |
| 276 | |
| 277 | class CustomDiffusionAttnProcessor: |
| 278 | def __call__( |
| 279 | self, |
| 280 | attn: CrossAttention, |
| 281 | hidden_states, |
| 282 | encoder_hidden_states=None, |
| 283 | attention_mask=None, |
| 284 | ): |
| 285 | batch_size, sequence_length, _ = hidden_states.shape |
| 286 | attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) |
| 287 | query = attn.to_q(hidden_states) |
| 288 | |
| 289 | crossattn = False |
| 290 | if encoder_hidden_states is None: |
| 291 | encoder_hidden_states = hidden_states |
| 292 | else: |
| 293 | crossattn = True |
| 294 | if attn.cross_attention_norm: |
| 295 | encoder_hidden_states = attn.norm_cross(encoder_hidden_states) |
| 296 | |
| 297 | key = attn.to_k(encoder_hidden_states) |
| 298 | value = attn.to_v(encoder_hidden_states) |
| 299 | if crossattn: |
| 300 | detach = torch.ones_like(key) |
| 301 | detach[:, :1, :] = detach[:, :1, :]*0. |
| 302 | key = detach*key + (1-detach)*key.detach() |
| 303 | value = detach*value + (1-detach)*value.detach() |
| 304 | |
| 305 | query = attn.head_to_batch_dim(query) |
| 306 | key = attn.head_to_batch_dim(key) |
| 307 | value = attn.head_to_batch_dim(value) |
| 308 | |
| 309 | attention_probs = attn.get_attention_scores(query, key, attention_mask) |
| 310 | hidden_states = torch.bmm(attention_probs, value) |
| 311 | hidden_states = attn.batch_to_head_dim(hidden_states) |
| 312 | |
| 313 | # linear proj |
| 314 | hidden_states = attn.to_out[0](hidden_states) |
| 315 | # dropout |
| 316 | hidden_states = attn.to_out[1](hidden_states) |
| 317 | |
| 318 | return hidden_states |
| 319 | |
| 320 | |
| 321 | class CustomDiffusionXFormersAttnProcessor: |
no outgoing calls
no test coverage detected