r""" Processor for implementing sliced attention with extra learnable key and value matrices for the text encoder. Args: slice_size (`int`, *optional*): The number of steps to compute attention. Uses as many slices as `attention_head_dim // slice_size`, and
| 1577 | |
| 1578 | |
| 1579 | class SlicedAttnAddedKVProcessor: |
| 1580 | r""" |
| 1581 | Processor for implementing sliced attention with extra learnable key and value matrices for the text encoder. |
| 1582 | |
| 1583 | Args: |
| 1584 | slice_size (`int`, *optional*): |
| 1585 | The number of steps to compute attention. Uses as many slices as `attention_head_dim // slice_size`, and |
| 1586 | `attention_head_dim` must be a multiple of the `slice_size`. |
| 1587 | """ |
| 1588 | |
| 1589 | def __init__(self, slice_size): |
| 1590 | self.slice_size = slice_size |
| 1591 | |
| 1592 | def __call__( |
| 1593 | self, |
| 1594 | attn: "Attention", |
| 1595 | hidden_states: torch.FloatTensor, |
| 1596 | encoder_hidden_states: Optional[torch.FloatTensor] = None, |
| 1597 | attention_mask: Optional[torch.FloatTensor] = None, |
| 1598 | temb: Optional[torch.FloatTensor] = None, |
| 1599 | ) -> torch.FloatTensor: |
| 1600 | residual = hidden_states |
| 1601 | |
| 1602 | if attn.spatial_norm is not None: |
| 1603 | hidden_states = attn.spatial_norm(hidden_states, temb) |
| 1604 | |
| 1605 | hidden_states = hidden_states.view(hidden_states.shape[0], hidden_states.shape[1], -1).transpose(1, 2) |
| 1606 | |
| 1607 | batch_size, sequence_length, _ = hidden_states.shape |
| 1608 | |
| 1609 | attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) |
| 1610 | |
| 1611 | if encoder_hidden_states is None: |
| 1612 | encoder_hidden_states = hidden_states |
| 1613 | elif attn.norm_cross: |
| 1614 | encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states) |
| 1615 | |
| 1616 | hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) |
| 1617 | |
| 1618 | query = attn.to_q(hidden_states) |
| 1619 | dim = query.shape[-1] |
| 1620 | query = attn.head_to_batch_dim(query) |
| 1621 | |
| 1622 | encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states) |
| 1623 | encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states) |
| 1624 | |
| 1625 | encoder_hidden_states_key_proj = attn.head_to_batch_dim(encoder_hidden_states_key_proj) |
| 1626 | encoder_hidden_states_value_proj = attn.head_to_batch_dim(encoder_hidden_states_value_proj) |
| 1627 | |
| 1628 | if not attn.only_cross_attention: |
| 1629 | key = attn.to_k(hidden_states) |
| 1630 | value = attn.to_v(hidden_states) |
| 1631 | key = attn.head_to_batch_dim(key) |
| 1632 | value = attn.head_to_batch_dim(value) |
| 1633 | key = torch.cat([encoder_hidden_states_key_proj, key], dim=1) |
| 1634 | value = torch.cat([encoder_hidden_states_value_proj, value], dim=1) |
| 1635 | else: |
| 1636 | key = encoder_hidden_states_key_proj |