SelfAttention和MultiHeadAttion实现demo

#encoding:utf-8

from math import sqrt

import torch

import torch.nn as nn

class Self_Attention(nn.Module):

def init(self, input_dim, dim_k, dim_v):

super(Self_Attention, self). init()

self.q = nn.Linear(input_dim, dim_k)

self.k = nn.Linear(input_dim, dim_k)

self.v = nn.Linear(input_dim, dim_v)

self.norm_fact = 1 / sqrt(dim_k)

def forward(self, x):

print("x.shape:", x.shape)

print("q.shape:", self.q.shape)

Q = self.q(x)

print("Q.shape:", Q.shape)

K = self.k(x)

print("K.shape:", K.shape)

V = self.v(x)

print("V.shape:", V.shape)

atten = nn.Softmax(dim=-1)(torch.bmm(Q,K.permute(0,2,1))) * self.norm_fact

output = torch.bmm(atten, V)

return output

print("\n")

print("self attention:")

x = torch.randn(4,3,1024)

print(x)

print("input size:", x.size())

self_attention = Self_Attention(1024,128,5)

res = self_attention(x)

print("\n")

print(res)

print("output size:", res.size())

print("\n")

class Self_Attention_Muti_Head(nn.Module):

def init(self, input_dim, dim_k, dim_v, nums_head):

super(Self_Attention_Muti_Head, self).init()

assert dim_k % nums_head == 0

assert dim_v % nums_head == 0

self.q = nn.Linear(input_dim, dim_k)

self.k = nn.Linear(input_dim, dim_k)

self.v = nn.Linear(input_dim, dim_v)

self.nums_head = nums_head

self.dim_k = dim_k

self.dim_v = dim_v

self._norm_fact = 1 / sqrt(dim_k)

def forward(self, x):

Q = self.q(x).reshape(-1, x.shape[0], x.shape[1], self.dim_k//self.nums_head)

K = self.k(x).reshape(-1, x.shape[0], x.shape[1], self.dim_k//self.nums_head)

V = self.v(x).reshape(-1, x.shape[0], x.shape[1], self.dim_v//self.nums_head)

print("x.shape:", x.shape)

print("Q.shape", Q.size())

atten = nn.Softmax(dim=-1)(torch.matmul(Q, K.permute(0,1,3,2)))

output = torch.matmul(atten, V).reshape(x.shape[0], x.shape[1], -1)

return output

print("\n")

print("multi head attention:")

x = torch.randn(4,3,1024)

print(x)

print(x.size())

self_attention = Self_Attention_Muti_Head(1024,128,6,2)

res = self_attention(x)

print("\n")

print(res)

print(res.size())


有个问题:

根据文献:https://arxiv.org/pdf/1911.02150.pdf,感觉这里说的Multi Head Attenion和 Group Query Attention意思是一样的:

这下面这张经典的图中的的Grouped-query意思是一样的:

哪里没理解到位?

相关推荐
jgyzl几秒前
2026.3.20 用EasyExcel实现excel报表的导入与导出
java·python·excel
weixin_433179338 分钟前
python - 正则表达式Regex
python·正则表达式
Riemann~~15 分钟前
ros2写一个可以修改参数的node
开发语言·python·ros2·机器人系统
盼小辉丶15 分钟前
PyTorch实战(36)——PyTorch自动机器学习
人工智能·pytorch·深度学习·自动机器学习
郝学胜-神的一滴15 分钟前
PyTorch 张量基础:零张量/一张量/指定值张量全解析
人工智能·pytorch·python
7yewh15 分钟前
Dense / 全连接层 / Gemm — 综合全局特征理解与运用
网络·人工智能·python·深度学习·cnn
智算菩萨17 分钟前
AGI神话:人工通用智能的幻象如何扭曲与分散数字治理的注意力
论文阅读·人工智能·深度学习·ai·agi
工业互联网专业20 分钟前
基于Python的黑龙江旅游景点数据分析系统的实现_flask+spider
python·flask·vue·毕业设计·源码·课程设计·spider
进击的小头27 分钟前
第14篇:MPC控制案例——无人机高度控制
python·算法·无人机
梦醒过后说珍重34 分钟前
Hugging Face 实战:从 Access Token 配置到突破 429 限流下载全记录
深度学习