由於公眾號改版不再按照作者的發布時間進行推送,為防止各位朋友錯過月來客棧推送的最新文章,大家可以手動將公眾號設置為「星標⭐」以第一時間獲得推送內容,感謝各位~
本開源項目為論文Attention is all you need的原理講解與項目實戰。講解文章近4萬餘字、50張圖、3個實戰示例,足以滿足你對Transformer的學習與掌握。
This post is all you need ——層層剝開Transformer(點擊進入)
從傳統的循環神經網絡的弊端在論文的摘要部分作者提到,現在主流的序列模型都是基於複雜的循環神經網絡或者是卷積神經網絡構造而來的Encoder-Decoder模型,並且就算是目前性能最好的序列模型也都是基於注意力機制下的Encoder-Decoder架構。為什麼作者會不停的提及這些傳統的Encoder-Decoder模型呢?接着,作者在介紹部分談到,由於傳統的Encoder-Decoder架構在建模過程中,下一個時刻的計算過程會依賴於上一個時刻的輸出,而這種固有的屬性就限制了傳統的Encoder-Decoder模型就不能以並行的方式進行計算,如圖1所示。
點擊進入討論區「NO. 0001」
This inherently sequential nature precludes parallelization within training examples, which becomes critical at longer sequence lengths, as memory constraints limit batching across examples.
因此,在這篇論文中,作者首次提出了一種全新的Transformer架構來解決這一問題。Transformer架構的優點在於它完全擯棄了傳統的循環結構,取而代之的是只通過注意力機制來計算模型輸入與輸出的隱含表示,而這種注意力的名字就是大名鼎鼎的自注意力機制(self-attention)。
To the best of our knowledge, however, the Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence- aligned RNNs or convolution.
總體來說,所謂自注意力機制就是通過某種運算來直接計算得到句子在編碼過程中每個位置上的注意力權重;然後再以權重和的形式來計算得到整個句子的隱含向量表示。最終,Transformer架構就是基於這種的自注意力機制而構建的Encoder-Decoder模型。
再到自注意力機制的原理首先需要明白一點的是,所謂的自注意力機制其實就是論文中所指代的」Scaled Dot-Product Attention「。在論文中作者說道,注意力機制可以描述為將query和一系列的key-value對映射到某個輸出的過程,而這個輸出的向量就是根據query和key計算得到的權重作用於value上的權重和。具體的,自注意力機制的結構如圖2和圖3所示。
An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is computed as a weighted sum of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.


不過從上面的計算結果還可以看到一點就是,模型在對當前位置的信息進行編碼時,會過度的將注意力集中於自身的位置(雖然這符合常識)而可能忽略了其它位置。因此,作者採取的一種解決方案就是採用多頭注意力機制(MultiHeadAttention),這部分內容我們將在稍後看到。
It expands the model’s ability to focus on different positions. Yes, in the example above, z1 contains a little bit of every other encoding, but it could be dominated by the the actual word itself.


從圖5可以看出,在交換位置前與交換位置後,與同一個權重矩陣進行線性變換後的結果截然不同。因此,這就證明通過Positional Embedding可以彌補自注意力機制不能捕捉序列時序信息的缺陷。
傳統Encoder-Decoder與Transformer解碼過程為了能夠更好的理解這裡Q、K、V的含義,我們先來看看傳統的基於Encoder-Decoder的Seq2Seq翻譯模型是如何進行解碼的,如圖6所示。

當第1個時刻的解碼過程完成之後,解碼器便會將解碼第1個時刻時的輸入,以及解碼第1個時刻後的輸出均作為解碼器的輸入來解碼預測第2個時刻的輸出。整個過程可以通過如圖7所示的過程來進行表示。

如圖8所示,在訓練過程中對於每一個樣本來說都需要這樣一個對稱矩陣來掩蓋掉當前時刻之後所有位置的信息。
因此在Transformer中,作者通過在生成訓練集的過程中記錄下每個樣本Padding的實際位置;然後再將注意力權重矩陣中對應位置的權重替換成負無窮便達到了忽略Padding位置信息的目的。這種做法也是Encoder-Decoder網絡結構中通用的一種辦法。

多層的Transformer網絡就是在兩邊分別堆疊了多個編碼器和解碼器的網絡模型,如圖10所示。

如圖10所示便是一個多層的Transformer網絡結構圖(原論文中採用了6個編碼器和6個解碼器),其中的每一個Encoder都是圖1中左邊所示的網絡結構(Decoder同理)。可以發現,它真的就是圖1堆疊後的形式。不過需要注意的是其整個解碼過程。
翻譯模型的實現代碼地址:https://github.com/moon-hotel/TransformerTranslation
在正式介紹如何構建數據集之前,我們先通過幾張圖來了解一下整個構建的流程,以便做到心中有數,不會迷路。

基於Transformer結構的文本分類模型
代碼地址:https://github.com/moon-hotel/TransformerClassification

代碼地址:https://github.com/moon-hotel/TransformerCouplet
