Attention Is All You Need简析

Attention Is All You Need

介绍

文章提出的transformer,使用注意力机制,对于资源的要求更低,却同样能达到state-of-the-art的效果。

整体框架

Attention Is All You Need简析

Encoder

Encoder由6个相同的层组成,每层都有两个子层,一个是self-attetion机制,一个是全连接的前向网络。在子层之间也使用了残差连接与layer nomalization。

Decoder

Decoder同样由6个相同的层组成,同样有两个相同的子层,同样利用残差连接与layer nomalization,不同的是插入了第三个子层,将encoder的输出作为输入来进行自注意力机制。值得注意的是,decoder采用的是masked self-attention。举个例子:

Attention Is All You Need简析

对于第一个单词i来说,只能与自己作attention,因为它无法预测它之后的信息,相应的每个单词只能与他和他之前的单词作attention。

Scaled Dot-Product Attention

Attention Is All You Need简析

Attention Is All You Need简析

该方法只是将query与key作点击后除以dk\sqrt{d_k}dkd_k是key的维度),其余并无不同

Multi-Head Attention

Attention Is All You Need简析

用h(本文取8)个不同的线性变换分别将dmodeld_{model}维的key、value和query线性变换成dkd_k维、dkd_k维和dvd_v维,然后再代入注意力机制,产生总共h×dvd_v维输出,然后拼起来,再用一个线性变换得到最终的输出。

Attention Is All You Need简析

Positional Encoding

Attention Is All You Need简析

这里不同于facebook采用绝对位置信息,而是利用正弦、余弦函数的周期性变换来表示相对位置。

Attention Is All You Need简析

位置p+k的向量可以表示成位置p的向量的线性变换,这提供了表达相对位置信息的可能性。

Position-wise Feed-forward Networks

在进行了Attention操作之后,encoder和decoder中的每一层都包含了一个全连接前向网络,对每个position的向量分别进行相同的操作,包括两个线性变换和一个ReLU**输出:

Attention Is All You Need简析

Experiment

Attention Is All You Need简析

可以看出,transformer 用了最少的资源得到了state-of-art的输出回报。