Attention相关问题笔试解析。

news2024/9/22 7:28:20

Attention相关问题笔试解析。

  • 题目描述一:【选择】
  • 题目描述二:【简答】
  • 题目描述三:【代码】
  • Scaled Dot-Product Attention:下面是用PyTorch实现的一个Attention机制的代码。这个实现包括一个简单的Scaled Dot-Product Attention机制和一个Multi-Head Attention机制。
  • Multi-Head Attention:
  • 无注释背诵版:

题目描述一:【选择】

Attention 机制中,输入QKV的shape为[N,L,D],请问 输出的shape和attention score 的shape分别是多少?
A. 输出:[N,L,D] attention score: [N,L,L,D]
B.输出:[N,L,D] attention score: [N,L,L]
C.输出:[N,L,L] attention score: [N,L,L,D]
D.输出:[N,L,L] attention score: [N,L,L]

正确答案是:B
在这里插入图片描述
在这里插入图片描述

题目描述二:【简答】

Transformer的核心思想是什么?它较之前的方法有什么优势(举例说明)?他和CNN有什么联系(开放问题)?

答:
Transformer的核心思想是使用自注意力机制(Self-Attention Mechanism)来建模序列数据中的依赖关系,取代传统的递归神经网络(RNN)和卷积神经网络(CNN)在处理序列任务时的局限性。具体来说,Transformer的架构主要由编码器(Encoder)和解码器(Decoder)组成,每个编码器和解码器模块由多头自注意力机制(Multi-Head Self-Attention Mechanism)和前馈神经网络(Feed-Forward Neural Network)组成。
在这里插入图片描述
在这里插入图片描述在这里插入图片描述
总结:
Transformer通过自注意力机制实现了高效的序列建模,克服了RNN在长距离依赖和并行处理上的局限性。它在自然语言处理(如机器翻译、文本生成)和其他序列任务中表现出色。虽然与CNN在结构上不同,但两者都能高效地进行特征提取和处理,并利用并行计算加速训练和推理过程。

题目描述三:【代码】

请使用torch 或者numpy 编写attention机制。QKV都是三维张量。

  • 实现一个attention 类
  • 需要说明函数入参含义、输入输出shape
  • 完成简单的scaled dot-product attention即可
  • 有把握的,可以实现multi-head attentlon

Scaled Dot-Product Attention:下面是用PyTorch实现的一个Attention机制的代码。这个实现包括一个简单的Scaled Dot-Product Attention机制和一个Multi-Head Attention机制。

首先,我们实现一个简单的Scaled Dot-Product Attention机制。

import torch
import torch.nn.functional as F

class ScaledDotProductAttention:
    def __init__(self, d_k):
        """
        初始化函数
        :param d_k: int, 每个attention头的维度
        """
        self.d_k = d_k

    def __call__(self, Q, K, V):
        """
        执行Scaled Dot-Product Attention
        :param Q: torch.Tensor, 形状为[N, L, D]
        :param K: torch.Tensor, 形状为[N, L, D]
        :param V: torch.Tensor, 形状为[N, L, D]
        :return: 输出张量的形状为[N, L, D], attention score的形状为[N, L, L]
        """
        # 计算注意力分数
        scores = torch.matmul(Q, K.transpose(-2, -1)) / torch.sqrt(torch.tensor(self.d_k, dtype=torch.float32))
        attention_scores = F.softmax(scores, dim=-1)
        
        # 计算注意力输出
        attention_output = torch.matmul(attention_scores, V)
        
        return attention_output, attention_scores

# 使用示例
N, L, D = 2, 5, 64
d_k = D

Q = torch.rand(N, L, D)
K = torch.rand(N, L, D)
V = torch.rand(N, L, D)

attention = ScaledDotProductAttention(d_k)
output, scores = attention(Q, K, V)

print(f"Output shape: {output.shape}")
print(f"Attention scores shape: {scores.shape}")

Multi-Head Attention:

接下来,我们实现一个Multi-Head Attention机制,它是基于多个Scaled Dot-Product Attention头的。

class MultiHeadAttention:
    def __init__(self, num_heads, d_model):
        """
        初始化函数
        :param num_heads: int, 注意力头的数量
        :param d_model: int, 输入的特征维度
        """
        assert d_model % num_heads == 0, "d_model必须是num_heads的整数倍"
        
        self.num_heads = num_heads
        self.d_model = d_model
        self.d_k = d_model // num_heads
        
        self.W_q = torch.nn.Linear(d_model, d_model)
        self.W_k = torch.nn.Linear(d_model, d_model)
        self.W_v = torch.nn.Linear(d_model, d_model)
        self.W_o = torch.nn.Linear(d_model, d_model)
        
        self.attention = ScaledDotProductAttention(self.d_k)

    def split_heads(self, x, batch_size):
        """
        将最后一维分裂成(num_heads, d_k)形状,并将张量重塑为(batch_size * num_heads, seq_length, d_k)
        :param x: torch.Tensor, 形状为(batch_size, seq_length, d_model)
        :param batch_size: int, batch大小
        :return: torch.Tensor, 形状为(batch_size * num_heads, seq_length, d_k)
        """
        x = x.view(batch_size, -1, self.num_heads, self.d_k)
        return x.transpose(1, 2).contiguous().view(batch_size * self.num_heads, -1, self.d_k)

    def __call__(self, Q, K, V):
        """
        执行Multi-Head Attention
        :param Q: torch.Tensor, 形状为[N, L, D]
        :param K: torch.Tensor, 形状为[N, L, D]
        :param V: torch.Tensor, 形状为[N, L, D]
        :return: 输出张量的形状为[N, L, D], attention score的形状为[N * num_heads, L, L]
        """
        batch_size = Q.size(0)
        
        Q = self.split_heads(self.W_q(Q), batch_size)
        K = self.split_heads(self.W_k(K), batch_size)
        V = self.split_heads(self.W_v(V), batch_size)
        
        attention_output, attention_scores = self.attention(Q, K, V)
        
        attention_output = attention_output.view(batch_size, self.num_heads, -1, self.d_k)
        attention_output = attention_output.transpose(1, 2).contiguous().view(batch_size, -1, self.d_model)
        
        return self.W_o(attention_output), attention_scores.view(batch_size, self.num_heads, -1, attention_scores.size(-1))

# 使用示例
N, L, D = 2, 5, 64
num_heads = 8
d_model = D

Q = torch.rand(N, L, D)
K = torch.rand(N, L, D)
V = torch.rand(N, L, D)

multi_head_attention = MultiHeadAttention(num_heads, d_model)
output, scores = multi_head_attention(Q, K, V)

print(f"Output shape: {output.shape}")
print(f"Attention scores shape: {scores.shape}")

在这里插入图片描述

以上实现了简单的Scaled Dot-Product Attention和Multi-Head Attention机制,并包含示例代码用于测试。

无注释背诵版:

  1. __init__是初始化d_k是每个向量的维度
  2. torch.matmul,转置K.transpose(-2, -1),/根号sqrt(d_k)
  3. F.softmax(scores, dim=-1)得注意力分数
  4. torch.matmul与V乘得输出
import torch
import torch.nn.functional as F

class Attention:
    def __init__(self, d_k): 
        self.d_k = d_k
    def __call__(self, Q, K, V):
        scores = torch.matmul(Q, K.transpose(-2, -1)) / torch.sqrt(torch.tensor(self.d_k, dtype=torch.float32))
        attention_scores = F.softmax(scores, dim=-1)
        attention_output = torch.matmul(attention_scores, V)
        return attention_output, attention_scores
    
class MultiHeadAttention:
    def __init__(self, num_heads, d_model):
        assert d_model % num_heads == 0
        self.nums_heads = num_heads
        self.d_model = d_model
        self.d_k = d_model // num_heads
        self.W_q = torch.nn.Linear(d_model, d_model)
        self.W_k = torch.nn.Linear(d_model, d_model)
        self.W_v = torch.nn.Linear(d_model, d_model)
        self.W_o = torch.nn.Linear(d_model, d_model)
        self.attention = Attention(self.d_k)

    def split_heads(self, x, batch_size):
        x = x.view(batch_size, -1, self.nums_heads, self.d_k)
        return x.transpose(1, 2).contiguous().view(batch_size * self.nums_heads, -1, self.d_k)
    
    def __call__(self, Q, K, V):
        batch_size = Q.size(0)
        Q = self.split_heads(self.W_q(Q), batch_size)
        K = self.split_heads(self.W_k(K), batch_size)
        V = self.split_heads(self.W_v(V), batch_size)
        attention_output, attention_score = self.attention(Q, K, V)
        attention_output = attention_output.view(batch_size, self.nums_heads, -1, self.d_k)
        attention_output = attention_output.transpose(1, 2).contiguous().view(batch_size, -1, self.d_model)
        return self.W_o(attention_output), attention_score.view(batch_size, self.nums_heads, -1, attention_score.size(-1))

使用示例

N, L, D = 2, 5, 64
num_heads = 8
d_model = D

Q = torch.rand(N, L, D)
K = torch.rand(N, L, D)
V = torch.rand(N, L, D)

multi_head_attention = MultiHeadAttention(num_heads, d_model)
output, scores = multi_head_attention(Q, K, V)

print(f"Output shape: {output.shape}")
print(f"Attention scores shape: {scores.shape}")

创作不易,观众老爷们请留步… 动起可爱的小手,点个赞再走呗 (๑◕ܫ←๑)
欢迎大家关注笔者,你的关注是我持续更博的最大动力


原创文章,转载告知,盗版必究



在这里插入图片描述


在这里插入图片描述
♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1696545.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

多模态交互式 AI 代理的兴起:探索 Google 的 Astra 和 OpenAI 的 ChatGPT-4o应用

OpenAI的发展 聊天GPT-4o 和 谷歌的阿斯特拉 标志着交互式人工智能代理的新阶段:多模式交互式人工智能代理的兴起。这次旅程开始于 Siri 和 Alexa的,它将语音激活的人工智能带入主流用途,并通过语音命令改变了我们与技术的交互。尽管有影响&a…

Rolla‘s homework:Image Processing with Python Final Project

对比学习Yolo 和 faster rcnn 两种目标检测 要求 Image Processing with Python Final Project Derek TanLoad several useful packages that are used in this notebook:Image Processing with Python Final Project Project Goals: • Gain an understanding of the object …

【python】python小区住房数据可视化(源码+数据)【独一无二】

👉博__主👈:米码收割机 👉技__能👈:C/Python语言 👉公众号👈:测试开发自动化【获取源码商业合作】 👉荣__誉👈:阿里云博客专家博主、5…

树莓派4B 有电但无法启动

试过多个SD卡,反复烧系统镜像都无法启动。接HDMI显示器没有信号输出,上电后PWR红灯长亮,ACT绿灯闪一下就不亮了,GPIO几个电源脚有电,芯片会发热,测量多个TP点电压好像都正常。 ……

【电子元件】TL431 电压基准

TL431(C23892)是一种常用的可调节精密电压基准和电压调节器。它广泛应用于电源管理、精密参考电压和稳压电路等领域。以下是TL431的一些关键特点和使用方法: 关键特点 可调输出电压:TL431的输出电压可以通过外部电阻网络在2.495V到36V范围内调整。精度高…

【笔记】Pytorch安装配置

参考视频 安装前建议预留至少10个G的空间,会省下很多麻烦 查看安装是否成功,可以在Anaconda Prompt里输入conda list查看conda环境是否配置了pytorch/torchvision 1.安装anaconda 2.安装 CUDA CUDA在官网直接安装即可,需要先查看自己电脑…

fpga问题整理

1、quartus联合modelsim仿真 无波形 问题: modelsim仿真无波形,打开transcript可以看到警告。 警告: # ** Warning: (vlog-2083) f:/program files/altera/ 13.1/quartus/ eda/sim_lib/ altera_lnsim.sv(22728): Carriage return (0x0D) is…

【前端笔记】Vue项目报错Error: Cannot find module ‘webpack/lib/RuleSet‘

网上搜了下发现原因不止一种,这里仅记录本人遇到的原因和解决办法,仅供参考 原因:因为某种原因导致本地package.json中vue/cli与全局vue/cli版本不同导致冲突。再次提示,这是本人遇到的,可能和大家有所不同&#xff0c…

子线程无法访问父线程中通过ThreadLocal设置的变量

学习过ThreadLocal的童鞋都知道,在子线程中,是无法访问父线程通过ThreadLocal设置的变量的。 package thread;/*** author heyunlin* version 1.0*/ public class ThreadLocalExample {public static void main(String[] args) throws InterruptedExcep…

搭建CMS系统

搭建CMS系统 1 介绍 内容管理系统(Content Management System,CMS)是一种用于管理、发布和修改网站内容的系统。开源的CMS系统有WordPress、帝国CMS等,国产的Halo很不错。 WordPress参考地址 # 官网 https://wordpress.org/# …

信号量——多线程

信号量的本质就是一个计数器 在多线程访问临界资源的时候,如果临界资源中又有很多份分好的资源,那么就可以通过信号量来表示里面还有多少份资源,且每份资源只有一个线程可以访问 线程申请信号量成功,就一定有一份资源是你的&…

SAP-技巧篇实现GUI免密码登录

做为上千万的软件怎么会没有免密码登录呢 01 — 背景需求 如何实现SAP GUI免密码登录,不输入密码实现系统自动登录。 免责声明:谨慎设置,因免密登录导致数据泄密,作者概不负责。 02 — 实现 客户端要求:SAP G…

微信小程序毕业设计-学生知识成果展示与交流系统项目开发实战(附源码+演示视频+LW)

大家好!我是程序猿老A,感谢您阅读本文,欢迎一键三连哦。 💞当前专栏:微信小程序毕业设计 精彩专栏推荐👇🏻👇🏻👇🏻 🎀 Python毕业设计…

17.分类问题

机器学习分类问题详解与实战 介绍 在机器学习中,分类问题是一类常见的监督学习任务,其目标是根据输入特征将数据样本划分为预先定义的类别之一。分类问题广泛应用于各个领域,如图像识别、自然语言处理、金融风险评估等。本文将详细介绍机器…

vue3瀑布流示例,左侧菜单根据窗口滚动条进行固定和取消固定,实现瀑布流demo

瀑布流demo的实现效果: 效果说明: 1.使用vue3实现瀑布流效果; 2.瀑布流横向设置5等分,可根据个人需求调整; 3.左侧菜单可根据右侧滚动条滑动时进行固定和取消固定,实现更优的展示效果; 4.瀑…

驱动命令之insmod depmod modprobe rmmod modinfo lsmod

insmod命令 insmod需指定所需加载模块的路径&#xff0c;且只加载所指定的模块&#xff0c;如果所指定的模块依赖于其他模块&#xff0c;insmod不会自动添加&#xff1b; 语法 insmod [-fkmpsvxX][-o <模块名称>][模块文件][符号名称 符号值] 参数说明&#xff1a; -f…

【代码随想录训练营】【Day 29】【回溯-3】| Leetcode 39, 41, 131

【代码随想录训练营】【Day 29】【回溯-3】| Leetcode 39&#xff0c; 41&#xff0c; 131 需强化知识点 startInex作用&#xff1a;一是处理是否可以有重复值&#xff0c;二是实现纵向遍历&#xff08;不能没有&#xff09;去重要在数组有序的前提下进行分割问题 题目 39.…

Comfyui工作流报错:Image scale to side 报错,安装了Derfuu-Nodes仍然没法运行

&#x1f386;问题描述 最近很多朋友在玩comfyui的时候&#xff0c;发现有个图像缩放的节点用不了了&#xff0c;同时报错&#xff1a; When loading the graph, the following node types were not found: Image scale to side Nodes that have failed to load will show as…