PyTorch
Adria / module /transformers /vanilla /multi_head_attention.py
Nebulon33's picture
Upload 84 files
bd992b7 verified
Raw History Blame Contribute Delete
2.55 kB
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
A very 'vanilla' implementation of batched multi-head attention.
Decoder only.
"""
class VanillaMultiHeadAttention(nn.Module):
def __init__(
self,
d_model: int = 512,
head_amount: int = 8
):
"""
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.
"""
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)
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<torch.Tensor, torch.Tensor>): 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)
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