1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class GroupedQueryAttention(nn.Module): def __init__(self, dim, n_heads, n_kv_heads): super().__init__() self.n_heads = n_heads self.n_kv_heads = n_kv_heads self.n_rep = n_heads // n_kv_heads self.wq = nn.Linear(dim, n_heads * head_dim, bias=False) self.wk = nn.Linear(dim, n_kv_heads * head_dim, bias=False) self.wv = nn.Linear(dim, n_kv_heads * head_dim, bias=False) self.wo = nn.Linear(n_heads * head_dim, dim, bias=False) def forward(self, x, mask=None, cache=None): bsz, seqlen, _ = x.shape xq = self.wq(x).view(bsz, seqlen, self.n_heads, head_dim) xk = self.wk(x).view(bsz, seqlen, self.n_kv_heads, head_dim) xv = self.wv(x).view(bsz, seqlen, self.n_kv_heads, head_dim) xk = xk.repeat_interleave(self.n_rep, dim=2) xv = xv.repeat_interleave(self.n_rep, dim=2) scores = torch.matmul(xq, xk.transpose(-2, -1)) / math.sqrt(head_dim) if mask is not None: scores = scores + mask attn = torch.softmax(scores, dim=-1) output = torch.matmul(attn, xv) return self.wo(output.reshape(bsz, seqlen, -1))
|