Attention Is All You Need 笔记

摘抄自:https://jalammar.github.io/illustrated-transformer/

1.Overall的定性理解

结构:
input–encoder–decoder–output
Attention Is All You Need 笔记

1.1 encoder part

encoder中包含数个相同结构的encoder layer(不共享权重),文章中用了六个(该数目可相应调整)。

每个encoder layer有两个sublayer:1. multi-head self-attention mechanism;2. position-wise fully connected feed-forward network

Attention Is All You Need 笔记
self-attention部分中各个embedding需要相互依赖,而FFNN中则是独立的,因此允许了并行运算。
Attention Is All You Need 笔记

数学part:
Attention Is All You Need 笔记

流程:输入word,转换为embedding,分别乘三个W矩阵得到Query vec, Key vec, Value vec (记为q, k, v). 当前处理第i个词,即看qi,用qi·kj(点乘)表示“在处理第i个词时,给到第j个词上的注意力分数”。由于dk变大会使点积结果增大数个数量级,因此除以根号dk(文章内dk为64,即除以8)。而后用softmax归一化。如图4所示。
Attention Is All You Need 笔记
而后用softmax后的分数乘上相应的vj,并做加和运算,得到该词的self-attention vec.

矩阵运算形式:
X: d.length * dx
WQ: dx * dk
WK: dx * dk
WV: dx*dv

Q=X x WQ d.len * dk
K,V 同理

Attention Is All You Need 笔记
Multi-Head:每一个encoder/decoder 不止用一套W,而是数套W(文中使用了8套),而后concat起来,组成d.len x 8dv维的矩阵,乘上Wo(8dv x do),得到最终的Z矩阵 (维数:d.len x do)。
Attention Is All You Need 笔记

positional encoding

见论文的3.5,大意为:因为该模型抛弃了RNN or CNN,因此为了利用序列的位置信息,引入了positional encoding,文中用的sin和cos函数(也可以用其他函数进行encode)

ResNet

文中使用了残差网络,即每一个sublayer的输出和输入相加并做normalize,我认为这样的目的是保留输入信息,因为有些层是不需要的、冗余的,为了让模型有能力忽略这些冗余层,我们直接把输入接到输出部分,使模型可以自主学习是否跳过冗余信息。
Attention Is All You Need 笔记

Decoder Unit

与encoder相似,输出矩阵(维度基于输出token数量和输出的do),其中每个do向量通过linear层转为长度为d.vocabulary的向量,并做softmax得到词典里哪个词概率最大。

参考文章中,是一个词一个词按序列输出的,对于这一点我也很不理解,这不又相当于用了点类似RNN的思想???

Attention Is All You Need 笔记