GQA (group query attention)

什么是GQA?

多个head的Query共用一组K和V。llama模型就用到该技术。

需要明确几点:

1.group有几组

2.每个group对应几个head

3.q以head为单位 k,v以group为单位 每个head/group特征维度都是head_dim

代码实现

python 复制代码
import torch.nn as nn
import torch
import math

# 自注意力
class GroupQueryAttention(nn.Module):
  def __init__(self, d_model, n_heads, n_groups):
    super().__init__()
    self.d_model = d_model
    self.n_heads = n_heads
    self.n_groups = n_groups

    assert d_model % n_heads == 0
    self.head_dim = d_model // n_heads
    # 每个group对应几个head
    self.heads_per_group = n_heads // n_groups

    # 以head为单位
    self.w_q = nn.Linear(d_model, n_heads*self.head_dim)  # n_heads*head_dim=d_model
    # 以group为单位
    self.w_k = nn.Linear(d_model, n_groups*self.head_dim)
    self.w_v = nn.Linear(d_model, n_groups*self.head_dim)

    self.w_combine = nn.Linear(d_model, d_model)
    self.softmax = nn.Softmax(dim=-1)
  
  # 给k,v进行复制,假设每个组对应3个head,那就要把每个组的数据复制3遍
  def expand(self, data): # data:k/v [b, group, seq_len, head_dim]
    b,_,seq_len,_ = data.shape
    data = data[:,:,None,:,:].expand(b, self.n_groups, self.heads_per_group, seq_len, self.head_dim)
    data = data.contiguous().view(b, -1, seq_len, self.head_dim)
    return data  # [b, group*heads_per_group, seq_len, head_dim]

  def forward(self, x, use_mask=False): # x: [b, seq_len, d_model]
    b, seq_len, _ = x.shape
    q,k,v = self.w_q(x), self.w_k(x), self.w_v(x)
    q = q.view(b, seq_len, self.n_heads, self.head_dim).permute(0,2,1,3)  # 以head为单位
    k = k.view(b, seq_len, self.n_groups, self.head_dim).permute(0,2,1,3) # 以group为单位
    v = v.view(b, seq_len, self.n_groups, self.head_dim).permute(0,2,1,3)

    # 复制
    k,v = self.expand(k), self.expand(v)
    score = q @ k.transpose(-1,-2) / math.sqrt(self.head_dim)
    if use_mask:
      mask = torch.tril(torch.ones(seq_len, seq_len))
      score = score.masked_fill(mask==0, float('-inf'))
    
    score = self.softmax(score) @ v
    score = score.permute(0,2,1,3).contiguous().view(b, seq_len, self.n_heads*self.head_dim)

    out = self.w_combine(score)
    return out

x = torch.rand(2,100,384)
model = GroupQueryAttention(384, 4, 2)
out = model(x)
print(out.shape)
相关推荐
估值探索者6 分钟前
【Python量化技术指标实战 02】MACD金叉也分强弱?手工算一次 DIF/DEA 就懂了
java·开发语言·python·股票数据·股票数据api接口
魔都吴所谓20 分钟前
【我的开源】Python实现一个离线 PDF 工具箱:架构、骑缝章与踩坑记录
python·pdf·开源
中烟创新29 分钟前
中烟创新×某烟草公司 | 企业综合管理平台:从“系统林立”到“一个平台”
人工智能·深度学习·中烟创新
拜小白30 分钟前
【论文讲解】PanelNet:用竖条面板理解360°室内环境
深度学习·计算机视觉·全景图
老鱼说AI39 分钟前
卷积神经网络的反向传播细节
人工智能·深度学习·神经网络·机器学习·计算机视觉·cnn·超分辨率重建
用户03321266636739 分钟前
Python 自动化办公:如何轻松在 PDF 中导入与导出表单数据
python
MoRanzhi12031 小时前
第5篇(上)· 使用 PyQt5 实现 2048 算法求解版:五类搜索算法内核
python·启发式算法·强化学习·搜索算法·蒙特卡洛树搜索·2048游戏·expectimax
星川皆无恙1 小时前
基于知识图谱的百科问答系统:Django + Neo4j 与实现
人工智能·python·机器学习·自然语言处理·django·知识图谱·neo4j
qq_448011161 小时前
EXEC字典沙箱仅是名字空间隔离,模块和解释器仍共享带来的坑
python
打工仔折腾 AI1 小时前
介入式脑机接口的跨尺度解码与闭环调控:从算法落地到后端工程实践
人工智能·后端·python·深度学习·算法·ai agent 实战