import torch import torch.nn as nn import torch.nn.functional as F from module.transformers.rope.rope import RoPE """ A very 'vanilla' implementation of batched multi-head attention. Modified to use RoPE positional embeddings for the Q and K values. Decoder only. """ class RoPEVanillaMultiHeadAttention(nn.Module): def __init__( self, d_model: int = 512, head_amount: int = 8, n_ctx: int = 2048, rope_base: float = 10000.0 ): """ Throws an error if d_model % head_amount != 0 d_model (int): The dimension of the model (embedding dimension size). head_amount (int): The number of attention heads. n_ctx (int): The maximum amount of expected context (used for RoPE scaling). """ super().__init__() assert d_model % head_amount == 0, f"Warning: Model dimensions ({d_model}) must be divisible by the number of attention heads ({head_amount})" self.d_model = d_model self.head_amount = head_amount self.d_k = d_model // head_amount self.c_attention = nn.Linear(d_model, 3 * d_model) self.c_projection = nn.Linear(d_model, d_model) self.rope = RoPE(self.d_k, n_ctx, rope_base) def forward(self, x: torch.Tensor, kv_cache: tuple[torch.Tensor, torch.Tensor] = None) -> tuple[ torch.Tensor, tuple[torch.Tensor, torch.Tensor]]: """ x (torch.Tensor): The input, of dim (B, T, C) where B (int): Batch size T (int): Time (Sequence Length) C (int): Channels (d_model) kv_cache (tuple): The kv cache. Should not be passed in as anything but the returned kv cache from a previous forward call. """ B, T, C = x.size() """ Q, K, V calculations qkv ends up as a tensor of size [B, T, 3 * d_model] """ qkv = self.c_attention(x) q, k, v = qkv.split(self.d_model, dim=2) q = q.view(B, T, self.head_amount, self.d_k).transpose(1, 2) k = k.view(B, T, self.head_amount, self.d_k).transpose(1, 2) v = v.view(B, T, self.head_amount, self.d_k).transpose(1, 2) q, k = self.rope(q, k, 0 if kv_cache is None else kv_cache[0].size(2)) if kv_cache is not None: k_cache, v_cache = kv_cache k = torch.cat([k_cache, k], dim=2) v = torch.cat([v_cache, v], dim=2) new_kv_cache = (k, v) # Torch's scaled_dot_product_attention implementation has FlashAttention and fancy things by default. # It's a little less satisfying in terms of actually showing the math, but faster # (And also removes the need to specify n_ctx) output = F.scaled_dot_product_attention(q, k, v, is_causal=(kv_cache is None)) output = output.transpose(1, 2).contiguous().view(B, T, C) return self.c_projection(output), new_kv_cache