当前位置: 首页 > news >正文

[动手学深度学习]注意力机制Transformer学习笔记

动手学深度学习(视频):68 Transformer【动手学深度学习v2】_哔哩哔哩_bilibili

动手学深度学习(pdf):10.7. Transformer — 动手学深度学习 2.0.0 documentation (d2l.ai)

李沐Transformer论文逐段精读:Transformer论文逐段精读【论文精读】_哔哩哔哩_bilibili

Vaswani, A. et al. (2017) 'Attention is all you need', 31st Conference on Neural Information Processing Systems (NIPS 2017), Long Beach, CA, USA. doi: https://doi.org/10.48550/arXiv.1706.03762

目录

1. Transformer

1.1. 整体实现步骤

1.2. Transformer理念

1.3. Transformer代码实现

1.4. Transformer弊端和局限

2. Transformer论文原文学习

2.1. Abstract

2.2. Introduction

2.3. Background

2.4. Model Architecture

2.4.1. Encoder and Decoder Stacks

2.4.2. Attention

2.4.3. Position-wise Feed-Forward Networks

2.4.4. Embeddings and Softmax

2.4.5. Positional Encoding

2.5.  Why Self-Attention

2.6. Training

2.6.1. Training Data and Batching

2.6.2. Hardware and Schedule

2.6.3. Optimizer

2.6.4. Regularization

2.7. Results

2.7.1. Machine Translation

2.7.2. Model Variations

2.7.3. English Constituency Parsing

2.8. Conclusion


1. Transformer

1.1. 整体实现步骤

(1)模型图

1.2. Transformer理念

(1)摒弃了传统费时的卷积和循环,仅采用注意力机制和全连接构成整个网络

(2)多使用残差连接

(3)Mask的提出

(4)李沐特地讲解了batch norm和layer norm的区别,主要是取的块不一样:

1.3. Transformer代码实现

(1)代码网址:GitHub - tensorflow/tensor2tensor: Library of deep learning models and datasets designed to make deep learning more accessible and accelerate ML research.

(2)李沐

        ①Encoder

class EncoderBlock(nn.Module):"""Transformer编码器块"""def __init__(self, key_size, query_size, value_size, num_hiddens,norm_shape, ffn_num_input, ffn_num_hiddens, num_heads,dropout, use_bias=False, **kwargs):super(EncoderBlock, self).__init__(**kwargs)self.attention = d2l.MultiHeadAttention(key_size, query_size, value_size, num_hiddens, num_heads, dropout,use_bias)self.addnorm1 = AddNorm(norm_shape, dropout)self.ffn = PositionWiseFFN(ffn_num_input, ffn_num_hiddens, num_hiddens)self.addnorm2 = AddNorm(norm_shape, dropout)def forward(self, X, valid_lens):Y = self.addnorm1(X, self.attention(X, X, X, valid_lens))return self.addnorm2(Y, self.ffn(Y))

        ②Decoder

class DecoderBlock(nn.Module):"""解码器中第i个块"""def __init__(self, key_size, query_size, value_size, num_hiddens,norm_shape, ffn_num_input, ffn_num_hiddens, num_heads,dropout, i, **kwargs):super(DecoderBlock, self).__init__(**kwargs)self.i = iself.attention1 = d2l.MultiHeadAttention(key_size, query_size, value_size, num_hiddens, num_heads, dropout)self.addnorm1 = AddNorm(norm_shape, dropout)self.attention2 = d2l.MultiHeadAttention(key_size, query_size, value_size, num_hiddens, num_heads, dropout)self.addnorm2 = AddNorm(norm_shape, dropout)self.ffn = PositionWiseFFN(ffn_num_input, ffn_num_hiddens,num_hiddens)self.addnorm3 = AddNorm(norm_shape, dropout)def forward(self, X, state):enc_outputs, enc_valid_lens = state[0], state[1]# 训练阶段,输出序列的所有词元都在同一时间处理,# 因此state[2][self.i]初始化为None。# 预测阶段,输出序列是通过词元一个接着一个解码的,# 因此state[2][self.i]包含着直到当前时间步第i个块解码的输出表示if state[2][self.i] is None:key_values = Xelse:key_values = torch.cat((state[2][self.i], X), axis=1)state[2][self.i] = key_valuesif self.training:batch_size, num_steps, _ = X.shape# dec_valid_lens的开头:(batch_size,num_steps),# 其中每一行是[1,2,...,num_steps]dec_valid_lens = torch.arange(1, num_steps + 1, device=X.device).repeat(batch_size, 1)else:dec_valid_lens = None# 自注意力X2 = self.attention1(X, key_values, key_values, dec_valid_lens)Y = self.addnorm1(X, X2)# 编码器-解码器注意力。# enc_outputs的开头:(batch_size,num_steps,num_hiddens)Y2 = self.attention2(Y, enc_outputs, enc_outputs, enc_valid_lens)Z = self.addnorm2(Y, Y2)return self.addnorm3(Z, self.ffn(Z)), state

1.4. Transformer弊端和局限

(1)位置信息表示弱

(2)长距离文本学习能力弱

2. Transformer论文原文学习

2.1. Abstract

(1)Bcakground: the sequence transduction model prevails with complicated convolution or recurrence.

(2)Purpose: they put forward a simple attention model without convolution or recurrence, which not only decreases the training time, but also increases the accuracy of translation

transduction  n.转导

2.2. Introduction

        ①Previous model: RNN, LSTM, gated RNN

        ②RNN limits in parallel computing in that it is highly rely on previous data

        ③Factorization tricks and conditional computation have made great achievement nowadays. However, reseachers are still unable to break free from the constraints of sequential computation.

        ④Attention mechanism can ignore the position of words

eschew  vt.避免;(有意地)避开;回避

2.3. Background

        ①Extended Neural GPU, ByteNet and ConvS2S try reducing the sequential mechanism. However, they still explode in distance computation.

        ②Self-attention, also named intra-attention has been used in "reading comprehension, abstractive summarization, textual entailment and learning task-independent sentence representations"

2.4. Model Architecture

        ①The Transformer model shows below:

Inputs are denoted by \left ( x_{1},x_{2}...x_{n} \right ) , then encode them to \left ( z_{1},z_{2}...z_{n} \right ) . Lastly decode z to \left ( y_{1},y_{2}...y_{m} \right ) (⭐input sequence and output sequence may not be of equal length).

        ②The model is auto-regressive

        ③The left of this figure is encode layer, and the right halves are decoder.

2.4.1. Encoder and Decoder Stacks

(1)Encoder

        ①N=6

        ②"Add" means adding x and sublayer(x), then using layer norm

(2)Decoder

        ①N=6

        ②Masked layer ensures x_{i} can only see the previous input of its position

2.4.2. Attention

(1)Scaled Dot-Product Attention

        ①The model shows below:

where Q denotes queries and K denotes keys of dimension d_{k}, V denotes values of dimension d_{v}

        ②The function of Scaled Dot-Product Attention:

\text{Attention}(Q,K,V)=\text{softmax}(\frac{QK^T}{\sqrt{d_k}})V

        ③They set \sqrt{d_{k}} as the dividend. They reckon when d_{k} increaces, additive attention outpeforms dot product attention.

        ④The more the dimension is, the less gradient the softmax is. Hence they scale the dot product.

(2) Multi-Head Attention

        ①The model shows below:

        ②The function of this block is:

\begin{aligned} \mathrm{MultiHead}(Q,K,V)& =\mathrm{Concat}(\mathrm{head}_{1},...,\mathrm{head}_{\mathrm{h}})W^{O} \\ \mathrm{where~head_{i}}& =\mathrm{Attention}(QW_{i}^{Q},KW_{i}^{K},VW_{i}^{V}) \end{aligned}

where all the W are parameter matrices. Additionally, h=8, and they set 

d_{k}=d_{v}=d_{\mathrm{model}}/h=64

(3)Applications of Attention in our Model

        ①Each position in the decoder participates in all positions in the input sequence

        ②Each position in the encoder can handle all positions in the previous layer of the encoder

        ③Mask all values on the right that have not yet appeared and represent them with -\infty (so when they participate in softmax layer, they always get 0)

2.4.3. Position-wise Feed-Forward Networks

        ① Function of fully connected feed-forward network:

\mathrm{FFN}(x)=\max(0,xW_1+b_1)W_2+b_2

where the input and output dimension d_{\mathrm{model}}=512 , and the inner-layer dimension d_{ff}=2048

2.4.4. Embeddings and Softmax

        ①The two embedding layers and the pre-softmax linear transformation are using the same weight matrix

        ②Table of different complexity for different layers:

where d denotes dimension, k denotes the size of convolutional kernal, n denotes length of sequence, and r is the size of the neighborhood in restricted self-attention

2.4.5. Positional Encoding

        ①Positional encodings:

\begin{aligned}PE_{(pos,2i)}&=sin(pos/10000^{2i/d_{\mathrm{model}}})\\PE_{(pos,2i+1)}&=cos(pos/10000^{2i/d_{\mathrm{model}}})\end{aligned}

where pos means position and i means dimension.

        ②They also tried learned positional embeddings, which got a similar result.

        ③Sinusoidal version allows longer sequence

2.5.  Why Self-Attention

        ①Low computational complexity, parallelized computation and short path length are the advantages of self-attention

        ②分析了一堆时间空间复杂度吗?我不是很看得懂

2.6. Training

2.6.1. Training Data and Batching

        They used WMT 2014 English-German dataset and WMT 2014 English-French dataset with 4.5 million sentence pairs and 36M sentences respectively.

2.6.2. Hardware and Schedule

        By each step in 1 second, they trained 300,000 steps (about 3.5 days)

2.6.3. Optimizer

        ①Adam optimizer: β1 = 0.9, β2 = 0.98 and ϵ = 10−9

        ②Learning rate: 

lrate=d_{\mathrm{model}}^{-0.5}\cdot\min(step\_num^{-0.5},step\_num\cdot warmup\_steps^{-1.5})

where warmup_steps = 4000 at the beginning

2.6.4. Regularization

        ①Dropout rate: 0.1

        ②Label smoothing value  \epsilon _{ls}=0.1 , which causes perplexity but increases accuracy and BLEU score

2.7. Results

2.7.1. Machine Translation

        Comparison of accuracy with other models:

2.7.2. Model Variations

        ①Variations of Transformer

where (A) changes the number of attention heads, attention key, and dimension of value, (B) adjusts the size of attention key, (C) and (D) control model size and dropout rate, (E) replaces sinusoidal positional encoding by learned positional embeddings. These ablation studies have successfully demonstrated the superiority of Transformer.

2.7.3. English Constituency Parsing

        ①Comparison table of generalization performance:

2.8. Conclusion

        ①This is the first model which only based on attention mechanism

        ②Outperforms any other previous model

相关文章:

[动手学深度学习]注意力机制Transformer学习笔记

动手学深度学习(视频):68 Transformer【动手学深度学习v2】_哔哩哔哩_bilibili 动手学深度学习(pdf):10.7. Transformer — 动手学深度学习 2.0.0 documentation (d2l.ai) 李沐Transformer论文逐段精读&a…...

hadoop集群安装并配置

文章目录 1.安装JDK 环境2.系统配置2.1修改本地hosts文件2.2创建hadoop 用户2.2 设置ssh免密(使用hadoop 用户生成) 3.安装 hadoop 3.2.43.1 安装hadoop3.1.1 配置Hadoop 环境变量 3.2配置 HDFS3.2.1 配置 workers 文件3.2.2 配置hadoop-env.sh3.2.3 配置…...

Quarto 入门教程 (3):代码框、图形、数据框设置

简介 本文是《手把手教你使用 Quarto 构建文档》第三期,前两期分别介绍了: 第一期 介绍了Quarto 构建文档的原理;可创建的文档类型;对应的参考资源分享。 第二期 介绍了如何使用 Quarto,并编译出文档(PDF…...

虚拟机Ubuntu18.04安装对应ROS版本详细教程!(含错误提示解决)

参考链接: Ubuntu18.04安装Ros(最新最详细亲测)_向日葵骑士Faraday的博客-CSDN博客 1.4 ROS的安装与配置_哔哩哔哩_bilibili ROS官网:http://wiki.ros.org/melodic/Installation/Ubuntu 一、检查cmake 安装ROS时会自动安装旧版的Cmake3.10.2。所以在…...

#力扣:14. 最长公共前缀@FDDLC

14. 最长公共前缀 一、Java class Solution {public String longestCommonPrefix(String[] strs) {for (int l 0; ; l) {for (int i 0; i < strs.length; i) {if (l > strs[i].length() || strs[i].charAt(l) ! strs[0].charAt(l)) return strs[0].substring(0, l);}…...

Android 13.0 解锁状态下禁止下拉状态栏功能实现

1.前言 在13.0的系统定制化开发中,在关于一些systemui下拉状态栏的定制化功能开发中,对于关于systemui的下拉状态栏 是否可以下拉做了定制,用系统属性来判断是否可以在解锁的情况下可以下拉状态栏布局,虽然11.0 12.0和13.0的关于 下拉状态栏相关分析有区别,可以通过分析相…...

chromium线程模型(1)-普通线程实现(ui和io线程)

通过chromium 官方文档&#xff0c;线程和任务一节我们可以知道 &#xff0c;chromium有两类线程&#xff0c;一类是普通线程&#xff0c;最典型的就是io线程和ui线程。 另一类是 线程池线程。 今天我们先分析普通线程的实现&#xff0c;下一篇文章分析线程池的实现。&#xff…...

uniapp uni.showToast 一闪而过的问题

问题&#xff1a;在页面跳转uni.navigateBack()等操作的前或后&#xff0c;执行uni.showToast&#xff0c;即使代码中设置2000ms的显示时间&#xff0c;也会一闪而过。 解决&#xff1a;用setTimeout延后navigateBack的执行。...

代理模式介绍及具体实现(设计模式 三)

代理模式是一种结构型设计模式&#xff0c;它允许通过创建一个代理对象来控制对另一个对象的访问 实例介绍和实现过程 假设我们正在开发一个电子商务网站&#xff0c;其中有一个商品库存管理系统。我们希望在每次查询商品库存之前&#xff0c;先进行权限验证&#xff0c;以确…...

【18】c++设计模式——>适配器模式

c的适配器模式是一种结构型设计模式&#xff0c;他允许将一个类的接口转换成另一个客户端所期望的接口。适配器模式常用于已存在的&#xff0c;但不符合新需求或者规范的类的适配。 在c中实现适配器模式时&#xff0c;通常需要一下几个组件&#xff1a; 1.目标接口&#xff08;…...

mariadb 错误日志中报错:Incorrect definition of table mysql.column_stats:

数据库错误日志出现此错误原因是因为系统表中字段类型或者数据结构有变动导致&#xff0c;一般是因为升级数据库版本后未同步升级系统表结构。 解决方法&#xff1a; 1.如果错误日志过大&#xff0c;直接删除。 2.执行 mysql_upgrade -u[用户名] -p[密码];&#xff0c;这一步…...

【SpringBoot】多环境配置和启动

环境分类&#xff0c;可以分为 本地环境、测试环境、生产环境等&#xff0c;通过对不同环境配置内容&#xff0c;来实现对不同环境做不同的事情。 SpringBoot 项目&#xff0c;通过 application-xxx.yml 添加不同的后缀来区分配置文件&#xff0c;启动时候通过后缀启动即可。 …...

跨qml通信

****Commet.qml //加载其他文件中的组件 不需要声明称Component //1.用loader.item.属性 访问属性 //2.loader.item.方法 访问方法 //3.用loader.item.方法.connect(槽)连接信号 Item { Loader{ id:loader; width: 200; …...

力扣-404.左叶子之和

Idea attention&#xff1a;先看清楚题目&#xff0c;题目说的是左叶子结点&#xff0c;不是左结点【泣不成声】 遇到像这种二叉树类型的题目呢&#xff0c;我们一般还是选择dfs&#xff0c;然后类似于前序遍历的方式加上判断条件即可 AC Code class Solution { public:void d…...

如何搭建一个 websocket

环境: NodeJssocket.io 4.7.2 安装依赖 yarn add socket.io创建服务器 引入文件 特别注意: 涉及到 colors 的代码&#xff0c;请采取 console.log() 打印 // 基础老三样 import http from "http"; import fs from "fs"; import { Server } from &quo…...

pip常用命令

TOC(pip常用命令) 1.pip 2.where pip 3.pip install --upgrade pip 4.安装 这里暂用flask库举例&#xff0c;安装flask库&#xff0c;默认安装最新版&#xff1a; pip install flask指定要安装flask库的版本&#xff1a; pip install flask版本号我们在安装第三方库时可…...

[QT编程系列-43]: Windows + QT软件内存泄露的检测方法

目录 一、如何查找Windows程序是否有内存泄露 二、如何定位Windows程序内存泄露的原因 二、Windows环境下内存监控工具的使用 2.1 内存监测工具 - Valgrind 2.2.1 Valgrind for Linux 2.2.2 Valgrind for Windows 2.2 内存监测工具 - Dr. Memory 2.2.1 特点 2.2.2 安装…...

【Java-LangChain:使用 ChatGPT API 搭建系统-5】处理输入-思维链推理

第五章&#xff0c;处理输入-思维链推理 在本章中&#xff0c;我们将专注于处理输入&#xff0c;即通过一系列步骤生成有用地输出。 有时&#xff0c;模型在回答特定问题之前需要进行详细地推理。如果您参加过我们之前的课程&#xff0c;您将看到许多这样的例子。有时&#xf…...

java Spring Boot RequestHeader设置请求头,当请求头中没有Authorization 直接400问题解决

我在接口中 写了一个接收请求头参数 Authorization 但是目前代理一个问题 那就是 当请求时 请求头中没有这个Authorization 就会直接因为参数不匹配 找不到指向 这里其实很简单 我们设置 value 为我们需要的字段内容 required 是否必填 我们设置为 false 就可以了 这样 没有也…...

[CISCN2019 华北赛区 Day1 Web5]CyberPunk 二次报错注入

buu上 做点 首先就是打开环境 开始信息收集 发现源代码中存在?file 提示我们多半是包含 我原本去试了试 ../../etc/passwd 失败了 直接伪协议上吧 php://filter/readconvert.base64-encode/resourceindex.phpconfirm.phpsearch.phpchange.phpdelete.php 我们通过伪协议全…...

RestClient

什么是RestClient RestClient 是 Elasticsearch 官方提供的 Java 低级 REST 客户端&#xff0c;它允许HTTP与Elasticsearch 集群通信&#xff0c;而无需处理 JSON 序列化/反序列化等底层细节。它是 Elasticsearch Java API 客户端的基础。 RestClient 主要特点 轻量级&#xff…...

Android Wi-Fi 连接失败日志分析

1. Android wifi 关键日志总结 (1) Wi-Fi 断开 (CTRL-EVENT-DISCONNECTED reason3) 日志相关部分&#xff1a; 06-05 10:48:40.987 943 943 I wpa_supplicant: wlan0: CTRL-EVENT-DISCONNECTED bssid44:9b:c1:57:a8:90 reason3 locally_generated1解析&#xff1a; CTR…...

shell脚本--常见案例

1、自动备份文件或目录 2、批量重命名文件 3、查找并删除指定名称的文件&#xff1a; 4、批量删除文件 5、查找并替换文件内容 6、批量创建文件 7、创建文件夹并移动文件 8、在文件夹中查找文件...

基于Uniapp开发HarmonyOS 5.0旅游应用技术实践

一、技术选型背景 1.跨平台优势 Uniapp采用Vue.js框架&#xff0c;支持"一次开发&#xff0c;多端部署"&#xff0c;可同步生成HarmonyOS、iOS、Android等多平台应用。 2.鸿蒙特性融合 HarmonyOS 5.0的分布式能力与原子化服务&#xff0c;为旅游应用带来&#xf…...

EtherNet/IP转DeviceNet协议网关详解

一&#xff0c;设备主要功能 疆鸿智能JH-DVN-EIP本产品是自主研发的一款EtherNet/IP从站功能的通讯网关。该产品主要功能是连接DeviceNet总线和EtherNet/IP网络&#xff0c;本网关连接到EtherNet/IP总线中做为从站使用&#xff0c;连接到DeviceNet总线中做为从站使用。 在自动…...

06 Deep learning神经网络编程基础 激活函数 --吴恩达

深度学习激活函数详解 一、核心作用 引入非线性:使神经网络可学习复杂模式控制输出范围:如Sigmoid将输出限制在(0,1)梯度传递:影响反向传播的稳定性二、常见类型及数学表达 Sigmoid σ ( x ) = 1 1 +...

[Java恶补day16] 238.除自身以外数组的乘积

给你一个整数数组 nums&#xff0c;返回 数组 answer &#xff0c;其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。 题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。 请 不要使用除法&#xff0c;且在 O(n) 时间复杂度…...

浅谈不同二分算法的查找情况

二分算法原理比较简单&#xff0c;但是实际的算法模板却有很多&#xff0c;这一切都源于二分查找问题中的复杂情况和二分算法的边界处理&#xff0c;以下是博主对一些二分算法查找的情况分析。 需要说明的是&#xff0c;以下二分算法都是基于有序序列为升序有序的情况&#xf…...

JVM暂停(Stop-The-World,STW)的原因分类及对应排查方案

JVM暂停(Stop-The-World,STW)的完整原因分类及对应排查方案,结合JVM运行机制和常见故障场景整理而成: 一、GC相关暂停​​ 1. ​​安全点(Safepoint)阻塞​​ ​​现象​​:JVM暂停但无GC日志,日志显示No GCs detected。​​原因​​:JVM等待所有线程进入安全点(如…...

推荐 github 项目:GeminiImageApp(图片生成方向,可以做一定的素材)

推荐 github 项目:GeminiImageApp(图片生成方向&#xff0c;可以做一定的素材) 这个项目能干嘛? 使用 gemini 2.0 的 api 和 google 其他的 api 来做衍生处理 简化和优化了文生图和图生图的行为(我的最主要) 并且有一些目标检测和切割(我用不到) 视频和 imagefx 因为没 a…...