Multi-Query Attention (MQA) PyTorch 实现

和多头注意力机制的唯一区别:K、V在不同的head之间实现了复用,而对于不同的头,Q依然不同。

因此这里的代码和标准多头注意力的实现也是几乎完全一样:

python 复制代码
import torch
import torch.nn as nn
import torch.nn.functional as F

class MultiQueryAttention(nn.Module):
    def __init__(self, embed_dim, num_heads):
        super().__init__()
        self.num_heads = num_heads
        self.head_dim = embed_dim // num_heads
        self.scale = self.head_dim ** -0.5

        # 查询、键、值投影
        self.q_proj = nn.Linear(embed_dim, embed_dim)  # 多头查询
        self.k_proj = nn.Linear(embed_dim, self.head_dim)  # 单头键
        self.v_proj = nn.Linear(embed_dim, self.head_dim)  # 单头值
        self.out_proj = nn.Linear(embed_dim, embed_dim)

    def forward(self, x):
        batch_size, seq_len, embed_dim = x.shape

        # 投影
        q = self.q_proj(x)  # (batch, seq_len, embed_dim)
        k = self.k_proj(x)  # (batch, seq_len, head_dim)
        v = self.v_proj(x)  # (batch, seq_len, head_dim)

        # 重塑查询为多头
        q = q.reshape(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
        # (batch, num_heads, seq_len, head_dim)
        
        # 键和值保持单头,扩展到多头维度
        k = k.unsqueeze(1)  # (batch, 1, seq_len, head_dim)
        v = v.unsqueeze(1)  # (batch, 1, seq_len, head_dim)

        # 注意力计算
        scores = torch.matmul(q, k.transpose(-2, -1)) * self.scale
        # (batch, num_heads, seq_len, seq_len)
        attn = F.softmax(scores, dim=-1)
        out = torch.matmul(attn, v)  # (batch, num_heads, seq_len, head_dim)

        # 合并多头
        out = out.transpose(1, 2).reshape(batch_size, seq_len, embed_dim)
        out = self.out_proj(out)  # (batch, seq_len, embed_dim)

        return out

# 示例用法
embed_dim = 64
num_heads = 8
model = MultiQueryAttention(embed_dim, num_heads)
x = torch.randn(2, 10, embed_dim)  # (batch, seq_len, embed_dim)
output = model(x)
print(output.shape)  # torch.Size([2, 10, 64])
相关推荐
花酒锄作田7 小时前
Postgres - Listen/Notify构建轻量级发布订阅系统
python·postgresql
Thomas.Sir7 小时前
第二章:LlamaIndex 的基本概念
人工智能·python·ai·llama·llamaindex
m0_694845577 小时前
Dify部署教程:从AI原型到生产系统的一站式方案
服务器·人工智能·python·数据分析·开源
李昊哲小课9 小时前
Python办公自动化教程 - 第7章 综合实战案例 - 企业销售管理系统
开发语言·python·数据分析·excel·数据可视化·openpyxl
不知名的老吴9 小时前
返回None还是空集合?防御式编程的关键细节
开发语言·python
李昊哲小课9 小时前
Python办公自动化教程 - 第5章 图表创建 - 让数据可视化
python·信息可视化·数据分析·数据可视化·openpyxl
chushiyunen9 小时前
python pygame实现贪食蛇
开发语言·python·pygame
Dream of maid9 小时前
Python-基础2(流程控制)
python
Lenyiin11 小时前
《Python 修炼全景指南:一》从环境搭建到第一个程序
开发语言·python
涛声依旧3931611 小时前
Python项目实战:学生信息管理系统
开发语言·python·数据挖掘