Attention processor used typically in processing the SD3-like self-attention projections.
| 1420 | |
| 1421 | |
| 1422 | class JointAttnProcessor2_0: |
| 1423 | """Attention processor used typically in processing the SD3-like self-attention projections.""" |
| 1424 | |
| 1425 | def __init__(self): |
| 1426 | if not hasattr(F, "scaled_dot_product_attention"): |
| 1427 | raise ImportError("JointAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.") |
| 1428 | |
| 1429 | def __call__( |
| 1430 | self, |
| 1431 | attn: Attention, |
| 1432 | hidden_states: torch.FloatTensor, |
| 1433 | encoder_hidden_states: torch.FloatTensor = None, |
| 1434 | attention_mask: torch.FloatTensor | None = None, |
| 1435 | *args, |
| 1436 | **kwargs, |
| 1437 | ) -> torch.FloatTensor: |
| 1438 | residual = hidden_states |
| 1439 | |
| 1440 | batch_size = hidden_states.shape[0] |
| 1441 | |
| 1442 | # `sample` projections. |
| 1443 | query = attn.to_q(hidden_states) |
| 1444 | key = attn.to_k(hidden_states) |
| 1445 | value = attn.to_v(hidden_states) |
| 1446 | |
| 1447 | inner_dim = key.shape[-1] |
| 1448 | head_dim = inner_dim // attn.heads |
| 1449 | |
| 1450 | query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) |
| 1451 | key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) |
| 1452 | value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) |
| 1453 | |
| 1454 | if attn.norm_q is not None: |
| 1455 | query = attn.norm_q(query) |
| 1456 | if attn.norm_k is not None: |
| 1457 | key = attn.norm_k(key) |
| 1458 | |
| 1459 | # `context` projections. |
| 1460 | if encoder_hidden_states is not None: |
| 1461 | encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states) |
| 1462 | encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states) |
| 1463 | encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states) |
| 1464 | |
| 1465 | encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view( |
| 1466 | batch_size, -1, attn.heads, head_dim |
| 1467 | ).transpose(1, 2) |
| 1468 | encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view( |
| 1469 | batch_size, -1, attn.heads, head_dim |
| 1470 | ).transpose(1, 2) |
| 1471 | encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view( |
| 1472 | batch_size, -1, attn.heads, head_dim |
| 1473 | ).transpose(1, 2) |
| 1474 | |
| 1475 | if attn.norm_added_q is not None: |
| 1476 | encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj) |
| 1477 | if attn.norm_added_k is not None: |
| 1478 | encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj) |
| 1479 |
no outgoing calls
no test coverage detected
searching dependent graphs…