笔记:读Attention Is All You Need


笔记:Attention Is All You Need

作者:Ashish Vaswani et al.,NIPS 2017.

目录

  • Motivation
  • Model
  • Attention

1 Motivation

本文使用self-attention代替RNN/CNN来实现encoder和decoder,原因有以下两点:

  • 使用注意力机制相比RNN并行度高
  • 使用注意力机制相比RNN能够更好的抓取长距离依赖

2 Model

本文模型架构总体上来看仍然是seq2seq架构,具体为encoder->decoder,如下图Figure1所示为模型整理架构。

2.1 Encoder

使用多层堆叠而成如图Figure1文中N=6,每层包括两个子层,分别为Multi-Head Attention层和FC全连接层。对比RNN建模的encoder(Bahdanau,D et al.,ICLR 2015.),align model即attention 得分或相关性矩阵计算使用\(s_{i-1}和h_j\)乘参数矩阵线性变换后相加得到,其中\(s_{i-1}\)为decoder(RNN实现)得隐状态即decoder生成,\(h_j\)为encoder隐状态即encoder生成。本文self-attention,Q、K、V分别对应RNN attention-encoder中的s、h、h,通过对输入语句得word embedding做线性映射得到,这里Q由于是self-attention来源于输入语句而非decoder,相似度计算使用dot product点积方式。同时为了模拟RNN编码时的位置信息加入了positional embedding这里也是一个重要的研究点文中采用sincos函数实现,原理没懂,获取positional embedding,结合方式即与input embedding相加,同时每个子层都是用了残差连接和layer normalization层内的归一化。

最后encoder(内部堆叠六层同样的结构)的输出作为decoder输入的一部分即K,V。

2.2 Decoder

相比encoder有几点不一样,首先每个堆叠的层中多了一个子层,encoder-decoder attention层,其次输入为output embedding即之前的decoder输出,至于第一次的输入以及其实输入就是加了mask的监督数据的y,详见参考。

经过其子层self-attention的输出作为encoder-decoder attention的输入即Q,相似度计算也是dot product。

2.4 小结

简单记录几点,具体见参考的几篇文章以及视频,讲的很细致清晰易懂,我就不在这里详细记笔记了,记了也是复述大佬们的,至此代码层面都没怎么下功夫,有些点还是看看代码后理解的应该会更好一些。

3 Attention

详细阅读参考,自己想明白之后,再看下图Figure 2很清晰。

参考

[1] Ashish Vaswani,Noam Shazeer,Niki Parmar,Jakob Uszkoreit,Llion Jones,Aidan N. Gomez,?ukasz Kaiser.Attention Is All You Need.NIPS 2017.

[2] Dzmitry Bahdanau,KyungHyun Cho,Yoshua Bengio.Neural Machine Translation by Jointly Learning to Align and Translate.ICLR 2015.

[3] 台大李宏毅21年机器学习课程 self-attention和transformer.https://www.bilibili.com/video/BV1Xp4y1b7ih?spm_id_from=333.1007.top_right_bar_window_custom_collection.content.click.

[4] 文哥的学习日记.一步步解析Attention is All You Need!.简书 2018.https://www.jianshu.com/p/b1030350aadb.

[5] 后青春期的工程师.《attention is all you need》解读.知乎 2019.https://zhuanlan.zhihu.com/p/34781297.

[6] soccer.Attention注意力机制与self-attention自注意力机制.知乎 2020.https://zhuanlan.zhihu.com/p/265108616.