MCPcopy Create free account
hub / github.com/Francis-Rings/MotionFollower / SlicedAttnProcessor

Class SlicedAttnProcessor

src/models/attn_process_diffuser.py:1492–1576  ·  view source on GitHub ↗

r""" Processor for implementing sliced attention. Args: slice_size (`int`, *optional*): The number of steps to compute attention. Uses as many slices as `attention_head_dim // slice_size`, and `attention_head_dim` must be a multiple of the `slice_size`.

Source from the content-addressed store, hash-verified

1490
1491
1492class SlicedAttnProcessor:
1493 r"""
1494 Processor for implementing sliced attention.
1495
1496 Args:
1497 slice_size (`int`, *optional*):
1498 The number of steps to compute attention. Uses as many slices as `attention_head_dim // slice_size`, and
1499 `attention_head_dim` must be a multiple of the `slice_size`.
1500 """
1501
1502 def __init__(self, slice_size: int):
1503 self.slice_size = slice_size
1504
1505 def __call__(
1506 self,
1507 attn: Attention,
1508 hidden_states: torch.FloatTensor,
1509 encoder_hidden_states: Optional[torch.FloatTensor] = None,
1510 attention_mask: Optional[torch.FloatTensor] = None,
1511 ) -> torch.FloatTensor:
1512 residual = hidden_states
1513
1514 input_ndim = hidden_states.ndim
1515
1516 if input_ndim == 4:
1517 batch_size, channel, height, width = hidden_states.shape
1518 hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
1519
1520 batch_size, sequence_length, _ = (
1521 hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
1522 )
1523 attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
1524
1525 if attn.group_norm is not None:
1526 hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
1527
1528 query = attn.to_q(hidden_states)
1529 dim = query.shape[-1]
1530 query = attn.head_to_batch_dim(query)
1531
1532 if encoder_hidden_states is None:
1533 encoder_hidden_states = hidden_states
1534 elif attn.norm_cross:
1535 encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
1536
1537 key = attn.to_k(encoder_hidden_states)
1538 value = attn.to_v(encoder_hidden_states)
1539 key = attn.head_to_batch_dim(key)
1540 value = attn.head_to_batch_dim(value)
1541
1542 batch_size_attention, query_tokens, _ = query.shape
1543 hidden_states = torch.zeros(
1544 (batch_size_attention, query_tokens, dim // attn.heads), device=query.device, dtype=query.dtype
1545 )
1546
1547 for i in range(batch_size_attention // self.slice_size):
1548 start_idx = i * self.slice_size
1549 end_idx = (i + 1) * self.slice_size

Callers 1

set_attention_sliceMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected