(
self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True
)
| 619 | ) |
| 620 | |
| 621 | def forward( |
| 622 | self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True |
| 623 | ): |
| 624 | # hidden_states: [sq, b, h] |
| 625 | |
| 626 | # ================================================= |
| 627 | # Pre-allocate memory for key-values for inference. |
| 628 | # ================================================= |
| 629 | # ===================== |
| 630 | # Query, Key, and Value |
| 631 | # ===================== |
| 632 | |
| 633 | # Attention heads [sq, b, h] --> [sq, b, (np * 3 * hn)] |
| 634 | mixed_x_layer = self.query_key_value(hidden_states) |
| 635 | |
| 636 | if self.multi_query_attention: |
| 637 | (query_layer, key_layer, value_layer) = mixed_x_layer.split( |
| 638 | [ |
| 639 | self.num_attention_heads_per_partition * self.hidden_size_per_attention_head, |
| 640 | self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head, |
| 641 | self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head, |
| 642 | ], |
| 643 | dim=-1, |
| 644 | ) |
| 645 | query_layer = query_layer.view( |
| 646 | query_layer.size()[:-1] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head) |
| 647 | ) |
| 648 | key_layer = key_layer.view( |
| 649 | key_layer.size()[:-1] + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head) |
| 650 | ) |
| 651 | value_layer = value_layer.view( |
| 652 | value_layer.size()[:-1] |
| 653 | + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head) |
| 654 | ) |
| 655 | else: |
| 656 | new_tensor_shape = mixed_x_layer.size()[:-1] + \ |
| 657 | (self.num_attention_heads_per_partition, |
| 658 | 3 * self.hidden_size_per_attention_head) |
| 659 | mixed_x_layer = mixed_x_layer.view(*new_tensor_shape) |
| 660 | |
| 661 | # [sq, b, np, 3 * hn] --> 3 [sq, b, np, hn] |
| 662 | (query_layer, key_layer, value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3) |
| 663 | |
| 664 | # apply relative positional encoding (rotary embedding) |
| 665 | if rotary_pos_emb is not None: |
| 666 | query_layer = apply_rotary_pos_emb(query_layer, rotary_pos_emb) |
| 667 | key_layer = apply_rotary_pos_emb(key_layer, rotary_pos_emb) |
| 668 | |
| 669 | # adjust key and value for inference |
| 670 | if kv_cache is not None: |
| 671 | cache_k, cache_v = kv_cache |
| 672 | key_layer = torch.cat((cache_k, key_layer), dim=0) |
| 673 | value_layer = torch.cat((cache_v, value_layer), dim=0) |
| 674 | if use_cache: |
| 675 | kv_cache = (key_layer, value_layer) |
| 676 | else: |
| 677 | kv_cache = None |
| 678 |
nothing calls this directly
no test coverage detected