Paper:2017年的Google机器翻译团队《Transformer:Attention Is All You Need》翻译并解读
Paper:2017年的Google機器翻譯團隊《Transformer:Attention Is All You Need》翻譯并解讀
目錄
論文評價
1、Motivation:
2、創新點:
Abstract ??
1、Introduction
2、Background
3、Model Architecture
3.1、Encoder and Decoder Stacks
3.2、Attention?
3.2.1、Scaled Dot-Product Attention
3.2.2、Multi-Head Attention? ?
3.2.3、Applications of Attention in our Model
3.3、Position-wise Feed-Forward Networks
3.4、Embeddings and Softmax
3.5、Positional Encoding
4、Why Self-Attention
5、Training
5.1、Training Data and Batching
5.2、Hardware and Schedule
5.3、Optimizer
5.4、Regularization?
6、Results
6.1、Machine Translation
6.2、Model Variations
6.3、English Constituency Parsing
7、Conclusion
References
論文評價
? ? ? ?2017年,Google機器翻譯團隊發表的《Attention is all you need》中大量使用了自注意力(self-attention)機制來學習文本表示。
參考文章:《attention is all you need》解讀
1、Motivation:
- 靠attention機制,不使用rnn和cnn,并行度高
- 通過attention,抓長距離依賴關系比rnn強
2、創新點:
- 通過self-attention,自己和自己做attention,使得每個詞都有全局的語義信息(長依賴
- 由于 Self-Attention 是每個詞和所有詞都要計算 Attention,所以不管他們中間有多長距離,最大的路徑長度也都只是 1。可以捕獲長距離依賴關系
- 提出multi-head attention,可以看成attention的ensemble版本,不同head學習不同的子空間語義。
論文地址
鏈接:《Attention Is All You Need》
PDF:《Attention Is All You Need》
Abstract ??
| The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include an encoder and a decoder. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train. Our model achieves 28.4 BLEUon the WMT 2014 English- to-German translation task, improving over the existing best results, including ensembles, by over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training costs of the best models from the literature. We show that the Transformer?generalizes well to other tasks by applying it successfully to English constituency parsing both with large and limited training data. | 主要的序列轉導模型是基于復雜的遞歸或卷積神經網絡,包括編碼器和解碼器。性能最好的模型還需通過注意機制連接編碼器和解碼器。我們提出了一種新的簡單的網絡結構,Transformer,它完全基于注意機制,完全不需要遞歸和卷積。在兩個機器翻譯任務上的實驗表明,這些模型具有更好的并行性和更少的訓練時間。我們的模型在WMT 2014英語到德語翻譯任務中達到28.4的BLEU,改進現有的最佳結果,包括集成,超過2 BLEU。在WMT 2014英法翻譯任務中,我們的模型在8個GPU上訓練3.5天后,建立了一個新的單模型最新的BLEU分數41.8,這是文獻中最好模型的訓練成本的一小部分。我們將該Transformer成功地應用于具有大量和有限訓練數據的英語選區句法分析中,證明了該變換器對其他任務具有良好的推廣效果。 |
注:BLEU是一種文本評估算法,即Bilingual Evaluation Understudy,它是用來評估機器翻譯跟專業人工翻譯之間的對應關系,核心思想就是機器翻譯越接近專業人工翻譯,質量就越好,經過BLEU算法得出的分數可以作為機器翻譯質量的其中一個指標。
1、Introduction
| Recurrent neural networks, long short-term memory [13] and gated recurrent [7] neural networks in particular, have been firmly established as state of the art approaches in sequence modeling and?transduction problems such as language modeling and machine translation [35, 2, 5]. Numerous efforts have since continued to push the boundaries of recurrent language models and encoder-decoder architectures [38, 24, 15]. ?Equal contribution. Listing order is random. Jakob proposed replacing RNNs with self-attention and started the effort to evaluate this idea. Ashish, with Illia, designed and implemented the first Transformer models and has been crucially involved in every aspect of this work. Noam proposed scaled dot-product attention, multi-head attention and the parameter-free position representation and became the other person involved in nearly every detail. Niki designed, implemented, tuned and evaluated countless model variants in our original codebase and tensor2tensor. Llion also experimented with novel model variants, was responsible for our initial codebase, and efficient inference and visualizations. Lukasz and Aidan spent countless long days designing various parts of and implementing tensor2tensor, replacing our earlier codebase, greatly improving results and massively accelerating our research. ??Work performed while at Google Brain. ??Work performed while at Google Research. | 遞歸神經網絡,特別是LSTM[13]和GRU[7]神經網絡,已經作為序列建模和轉導問題(如語言建模和機器翻譯[35,2,5])的最新方法被牢固地建立起來。此后,無數的努力繼續推進遞歸語言模型和編碼器-解碼器體系結構的界限[38,24,15]。 *同等貢獻。列表順序是隨機的。Jakob建議用self-attention取代RNNs,并開始努力評估這個想法。Ashish和Illia一起設計并實現了第一個Transformer 模型,并在這項工作的各個方面都有重要的參與。Noam提出了標度點積注意、多頭注意和無參數位置表示,成為幾乎涉及每個細節的另一個人。Niki在我們最初的代碼庫和tensor2tensor中設計、實現、調整和評估了無數的模型變體。Llion還試驗了新的模型變體,負責我們的初始代碼庫,以及有效的推理和可視化。Lukasz和Aidan花了無數天的時間設計和實現Tensor2Sensor的各個部分,取代了我們早期的代碼庫,極大地改進了結果,極大地加速了我們的研究。在谷歌大腦工作期間完成的工作。?在谷歌研究所工作期間完成的工作。 |
| Recurrent models typically factor computation along the symbol positions of the input and output sequences. Aligning the positions to steps in computation time, they generate a sequence of hidden states ht, as a function of the previous hidden state ht?1 and the input for position t. This inherently ?sequential nature precludes parallelization within training examples, which becomes critical at longer ?sequence lengths, as memory constraints limit batching across examples. Recent work has achieved significant improvements in computational efficiency through factorization tricks [21] and conditional computation [32], while also improving model performance in case of the latter. The fundamental constraint of sequential computation, however, remains. ? ? | 遞歸模型通常沿輸入和輸出序列的符號位置進行因子計算。將位置與計算時間中的步驟對齊,它們生成隱藏狀態的序列ht,作為先前隱藏狀態ht-1和位置t的輸入的函數。這種固有的序列性質排除了訓練示例中的并行化,而在較長的序列長度下,并行化變得至關重要,因為內存限制限制了跨示例的批處理。最近的工作通過因子分解技巧[21]和條件計算[32]在計算效率方面取得了顯著的提高,同時也提高了后者的模型性能。然而,順序計算的基本約束仍然存在。 ?? |
| Attention mechanisms have become an integral part of compelling sequence modeling and transduc- tion models in various tasks, allowing modeling of dependencies without regard to their distance in the input or output sequences [2, 19]. In all but a few cases [27], however, such attention mechanisms are used in conjunction with a recurrent network. ? ? | 注意機制已經成為各種任務中強制序列建模和轉換模型的一個組成部分,允許不考慮輸入或輸出序列中的距離的依賴關系建模[2,19]。然而,在除少數情況外的所有情況下[27],這種注意機制都與一個遞歸網絡結合使用。 ?? |
| In this work we propose the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output. The Transformer allows for significantly more parallelization and can reach a new state of the art in translation quality after being trained for as little as twelve hours on eight P100 GPUs. | 在這項工作中,我們提出了Transformer,這是一種避免重復出現的模型架構,而完全依賴于注意機制來繪制輸入和輸出之間的全局依賴關系。該Transformer 允許更顯著的并行化,并可以達到一個新的水平,在翻譯質量后,在8個P100 gpu訓練了12小時。 |
2、Background
| The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU [16], ByteNet [18] and ConvS2S [9], all of which use convolutional neural networks as basic building block, computing hidden representations in parallel for all input and output positions. In these models, the number of operations required to relate signals from two arbitrary input or output positions grows in the distance between positions, linearly for ConvS2S and logarithmically for ByteNet. This makes it more difficult to learn dependencies between distant positions [12]. In the Transformer this is reduced to a constant number of operations, albeit at the cost of reduced effective resolution due to averaging attention-weighted positions, an effect we counteract with Multi-Head Attention as described in section 3.2. | 減少順序計算的目的也形成了擴展神經GPU〔16〕、ByteNet〔18〕和VusS2S〔9〕的基礎,所有這些都使用卷積神經網絡作為基本構建塊,并行計算所有輸入和輸出位置的隱藏表示。在這些模型中,將來自兩個任意輸入或輸出位置的信號關聯起來所需的操作數在位置之間的距離中增長,convs2為線性增長,ByteNet為對數增長。這使得學習遠距離位置之間的依賴性變得更加困難[12]。在Transformer 中,這被減少到一個恒定的操作數,盡管由于平均注意加權位置而降低了有效分辨率,但是我們用多頭注意抵消了這一影響,如第3.2節所述。 |
| Self-attention, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence. Self-attention has been used successfully in a variety of tasks including reading comprehension, abstractive summarization, textual entailment and learning task-independent sentence representations [4, 27, 28, 22]. | Self-attention,有時稱為注意內注意,是一種注意機制,它將單個序列的不同位置聯系起來,以計算序列的表示。Self-attention在閱讀理解、抽象概括、語篇蘊涵和學習任務無關的句子表征等任務中得到了成功的運用[4,27,28,22]。 |
| End-to-end memory networks are based on a recurrent attention mechanism instead of sequence- aligned recurrence and have been shown to perform well on simple-language question answering and language modeling tasks [34]. | 端到端的記憶網絡是基于一種循環注意機制而不是順序排列的循環,并且已經被證明在簡單的語言問答和語言建模任務中表現良好[34]。 |
| 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. In the following sections, we will describe the Transformer , motivate self-attention and discuss its advantages over models such as [17, 18] and [9]. | 然而,據我們所知,Transformer 是第一個完全依賴于self-attention來計算其輸入和輸出表示的傳導模型,而不使用序列對齊的RNN或卷積。在下面的章節中,我們將描述Transformer ,激發self-attention,并討論其相對于[17,18]和[9]等模型的優勢。 |
3、Model Architecture
| Most competitive neural sequence transduction models have an encoder-decoder structure [5, 2, 35]. Here, the encoder maps an input sequence of symbol representations (x1, ..., xn) to a sequence of continuous representations z = (z1, ..., zn). Given z, the decoder then generates an output sequence (y1, ..., ym) of symbols one element at a time. At each step the model is auto-regressive [10], consuming the previously generated symbols as additional input when generating the next. | 大多數競爭性神經序列轉導模型都具有編碼器-解碼器結構[5,2,35]。這里,編碼器將符號表示的輸入序列(x1,…,xn)映射到連續表示的序列z=(z1,…,zn)。給定z,解碼器然后一次生成一個符號的輸出序列(y1,…,ym)。在每一步,模型都是自回歸的[10],在生成下一步時,將先前生成的符號作為附加輸入。 |
| The Transformer follows this overall architecture using stacked self-attention and point-wise, fully connected layers for both the encoder and decoder, shown in the left and right halves of Figure 1, respectively. | Transformer 遵循這個總體架構,使用堆疊的自關注層和點方式的完全連接層,分別用于編碼器和解碼器,如圖1的左半部分和右半部分所示。 |
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Figure 1: The Transformer - model architecture.
3.1、Encoder and Decoder Stacks
| Encoder:?The encoder is composed of a stack of?N?= 6 identical layers. Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position- wise fully connected feed-forward network. We employ a residual connection [11] around each of the two sub-layers, followed by layer normalization [1]. That is, the output of each sub-layer is LayerNorm(x?+ Sublayer(x)), where Sublayer(x) is the function implemented by the sub-layer itself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding layers, produce outputs of dimension?dmodel?= 512. | 編碼器:編碼器由N=6個相同層組成。每層有兩個子層。 第一層是多頭multi-head?self-attention機制, 第二層是一個簡單的、位置全連接的前饋網絡。我們在兩子層的每一個子層周圍使用一個殘差連接[11],然后是層規范化[1]。也就是說,每個子層的輸出是 LayerNorm(x?+ Sublayer(x)), 其中Sublayer(x) 是子層本身實現的功能。為了方便這些殘差連接,模型中的所有子層以及嵌入層都會生成維d model=512的輸出。 |
| Decoder:?The decoder is also composed of a stack of?N?= 6 identical layers. In addition to the two sub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head attention over the output of the encoder stack. Similar to the encoder, we employ residual connections around each of the sub-layers, followed by layer normalization. We also modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions. This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position?i?can depend only on the known outputs at positions less than?i. | 解碼器:解碼器也由N=6個相同層組成。除了每個編碼器層中的兩個子層之外,解碼器還插入第三個子層,該子層對編碼器堆棧的輸出執行multi-head attention。與編碼器類似,我們在每個子層周圍使用殘差連接,然后進行層規范化。我們還修改解碼器堆棧中的自關注子層,以防止位置關注后續位置。這種掩蔽加上輸出嵌入偏移一個位置的事實,確保位置i的預測只能依賴于小于i的位置處的已知輸出。 |
3.2、Attention?
| 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. | 一個注意函數可以描述為將查詢和一組鍵值對映射到輸出,其中query, keys, values和output 都是向量。輸出被計算為值的加權和,其中分配給每個值的權重由查詢的兼容函數和相應的鍵計算。 |
Figure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel.
圖2:(左)縮放點積注意力機制? ? ? ? ? (右圖)多頭注意力機制由幾個平行運行的注意力層組成。
3.2.1、Scaled Dot-Product Attention
| We call our particular attention "Scaled Dot-Product Attention" (Figure 2).?The input consists of queries and keys of dimension?dk?, and values of dimension?dv?. We compute the dot products of the query with all keys, divide each by?, and apply a softmax function to obtain the weights on the values. | 我們稱特別注意為“縮放點積注意”(圖2)。輸入由維度dk的查詢和鍵以及維度dv的值組成。我們使用所有鍵計算查詢的點積,用√dk除以每個鍵,然后應用softmax函數獲得值的權重。 ? |
| In practice, we compute the attention function on a set of queries simultaneously, packed together into a matrix?Q. The keys and values are also packed together into matrices?K?and?V?. We compute the matrix of outputs as: | 在實際應用中,我們同時計算一組查詢的注意函數,將它們組合成一個矩陣Q,并將鍵和值組合成矩陣K和V。我們將輸出矩陣計算為: |
| The two most commonly used attention functions are additive attention [2], and dot-product (multiplicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor. Additive attention computes the compatibility function using a feed-forward network witha single hidden layer. While the two are similar in theoretical complexity, dot-product attention ismuch faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code. | 最常用的兩個注意函數是additive attention[2]和dot-product?attention(乘法)。dot-product?attention與我們的算法相同,除了比例因子。additive attention使用具有單個隱藏層的前饋網絡計算兼容性函數。雖然這兩種方法在理論復雜度上是相似的,但是由于它可以用高度優化的矩陣乘法碼來實現,所以在實際應用中,dot-product?attention要快得多,空間也更有效。 ? |
| While for small values of dk the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of dk [3]. We suspect that for large values of dk , the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients 4. To counteract this effect, we scale the dot products by | 而對于dk的小值,兩種機制的表現相似,additive attention優于dot product attention,而對于dk的大值則沒有標度[3]。我們懷疑,對于dk的大值,點積在數量級上增長很大,將softmax函數推到梯度非常小的區域4。為了抵消這一影響,我們將 dot products積按 |
3.2.2、Multi-Head Attention? ?
| Instead of performing a single attention function with dmodel-dimensional keys, values and queries, we found it beneficial to linearly project the queries, keys and values h times with different, learned linear projections to dk , dk and dv dimensions, respectively. On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding dv -dimensional output values. These are concatenated and once again projected, resulting in the final values, as depicted in Figure 2.Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this. | 我們發現,不同于使用dmodel維度的鍵、值和查詢來執行單一的注意功能,將查詢、鍵和值分別以不同的線性投影h次線性投影到dk、dk和dv維度是有益的。 然后,在這些查詢、鍵和值的投影版本中,我們并行地執行注意功能,生成dv維輸出值。如圖2所示,這些被連接起來并再次投影,從而產生最終值。Multi-head attention允許模型共同關注來自不同位置的不同表示子空間的信息。只有一個注意力集中的頭腦,平均化可以抑制這種情況。 |
| In this work we employ h = 8 parallel attention layers, or heads. For each of these we use dk = dv = dmodel/h = 64. Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality. | 在這項工作中,我們使用了h=8個平行的注意層,或者說頭部。對于每一個,我們使用dk=dv=dmodel/h=64。由于每個頭部的維數減少,總的計算成本與全維度的單頭部注意的計算成本相似。 |
3.2.3、Applications of Attention in our Model
| The Transformer uses multi-head attention in three different ways:
| Transformer 以三種不同的方式使用multi-head:
|
3.3、Position-wise Feed-Forward Networks
| In addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully connected feed-forward network, which is applied to each position separately and identically. This consists of two linear transformations with a ReLU activation in between. | 除了注意力子層之外,我們的編碼器和解碼器中的每一層都包含一個完全連接的前饋網絡,該網絡分別且相同地應用于每個位置。。這包括兩個線性變換,中間有一個ReLU激活。 FFN(x)=max(0,xW1+b1)W2+b2 |
| While the linear transformations are the same across different positions, they use different parameters from layer to layer. Another way of describing this is as two convolutions with kernel size 1. The dimensionality of input and output is dmodel = 512, and the inner-layer has dimensionality df f = 2048. | 雖然不同位置的線性變換是相同的,但它們在不同的層之間使用不同的參數。另一種描述方法是兩個核大小為1的卷積。輸入輸出的維數為dmodel=512,內層的維數為df f=2048。 |
3.4、Embeddings and Softmax
| Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of dimension dmodel. We also use the usual learned linear transfor- mation and softmax function to convert the decoder output to predicted next-token probabilities. In our model, we share the same weight matrix between the two embedding layers and the pre-softmax?linear transformation, similar to [30]. In the embedding layers, we multiply those weights by √dmodel. | 與其他序列轉換模型類似,我們使用學習的嵌入來將輸入標記和輸出標記轉換為維度dmodel的向量。我們還使用通常的學習線性變換和softmax函數將解碼器輸出轉換為預測的下一個令牌概率。在我們的模型中,我們在兩個嵌入層和pre-softmax線性變換之間共享相同的權重矩陣,類似于[30]。在嵌入層中,我們將這些權重乘以√dmodel。 |
3.5、Positional Encoding
| Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the?tokens in the sequence. To this end, we add "positional encodings" to the input embeddings at the bottoms of the encoder and decoder stacks. The positional encodings have the same dimension dmodel as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed [9]. | 由于我們的模型不包含遞歸和卷積,為了使模型能夠利用序列的順序,我們必須注入一些關于序列中標記的相對或絕對位置的信息。為此,我們將“位置編碼”添加到編碼器和解碼器堆棧底部的輸入嵌入中。位置編碼與嵌入編碼具有相同的維度dmodel,因此可以將它們相加。有許多位置編碼的選擇,學習和固定的[9]。 |
| Table 1: Maximum path lengths, per-layer complexity and minimum number of sequential operations for different layer types. n is the sequence length, d is the representation dimension, k is the kernel size of convolutions and r the size of the neighborhood in restricted self-attention. | 表1:不同層類型的最大路徑長度、每層復雜度和最小順序操作數。 n為序列長度, d為表示維數, k為卷積的核大小, r為受限自我注意的鄰域大小。 |
| In this work, we use sine and cosine functions of different frequencies: where pos is the position and i is the dimension. That is, each dimension of the positional encoding corresponds to a sinusoid. The wavelengths form a geometric progression from 2π to 10000 · 2π. We chose this function because we hypothesized it would allow the model to easily learn to attend by relative positions, since for any fixed offset k, P Epos+k can be represented as a linear function of P Epos. | 在這項工作中,我們使用不同頻率的正弦和余弦函數: 也就是說,位置編碼的每個維度對應于一個正弦。波長形成了從2π到10000·2π的幾何級數。我們選擇這個函數是因為我們假設它可以讓模型很容易地學會通過相對位置來參與,因為對于任何固定偏移量k,P-Epos+k可以表示為P-Epos的線性函數。 |
| We also experimented with using learned positional embeddings [9] instead, and found that the two versions produced nearly identical results (see Table 3 row (E)). We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training. | 我們還嘗試使用學習的位置嵌入[9],發現這兩個版本產生了幾乎相同的結果(見表3第(E)行)。我們之所以選擇正弦曲線,是因為它可能允許模型外推到比訓練中遇到的序列長度更長的序列。 |
4、Why Self-Attention
| In this section we compare various aspects of self-attention layers to the recurrent and convolu- tional layers commonly used for mapping one variable-length sequence of symbol representations (x1, ..., xn) to another sequence of equal length (z1, ..., zn), with xi, zi ∈ Rd, such as a hidden layer in a typical sequence transduction encoder or decoder. Motivating our use of self-attention we consider three desiderata. | 在本節中,我們將self-attention層的各個方面與通常用于映射一個可變長度的符號表示序列(x1,…,xn)到另一個等長序列(Z1,…,Zn)的遞歸和卷積層進行比較。例如典型的序列轉換編碼器或解碼器中的隱藏層。激發我們使用self-attention,我們考慮三個目的。 ? |
|
? |
| As noted in Table 1, a self-attention layer connects all positions with a constant number of sequentially executed operations, whereas a recurrent layer requires O(n) sequential operations. In terms of computational complexity, self-attention layers are faster than recurrent layers when the sequence length n is smaller than the representation dimensionality d, which is most often the case with sentence representations used by state-of-the-art models in machine translations, such as word-piece [38] and byte-pair [31] representations. To improve computational performance for tasks involving very long sequences,self-attention could be restricted to considering only a neighborhood of size r in the input sequence centered around the respective output position. This would increase the maximum path length to O(n/r). We plan to investigate this approach further in future work. | 如表1所示,self-attention層用固定數量的順序執行的操作連接所有位置,而遞歸層需要O(n)順序操作。在計算復雜性方面,當序列長度N小于表示維度D時,自關注層比遞歸層更快,這是最常用的機器翻譯中最先進的模型所使用的句子表示的情況,例如Word(38)和字節對(31)表示。為了提高包含很長序列的任務的計算性能,可以將self-attention限制為僅考慮以各自輸出位置為中心的輸入序列中r大小的鄰域。這將增加到O(n/r)的最大路徑長度。我們計劃在今后的工作中進一步研究這種方法。 ? |
| A single convolutional layer with kernel width k < n does not connect all pairs of input and output positions. Doing so requires a stack of O(n/k) convolutional layers in the case of contiguous kernels, or O(logk (n)) in the case of dilated convolutions [18], increasing the length of the longest paths between any two positions in the network. Convolutional layers are generally more expensive than recurrent layers, by a factor of k. Separable convolutions [6], however, decrease the complexity considerably, to O(k · n · d + n · d2). Even with k = n, however, the complexity of a separable convolution is equal to the combination of a self-attention layer and a point-wise feed-forward layer, the approach we take in our model. | 核寬度k<n的單個卷積層不能連接所有輸入和輸出位置對。這樣做需要一堆O(n/k)卷積層(對于相鄰的核),或者O(logk(n))卷積層(對于擴展卷積)[18],增加網絡中任意兩個位置之間最長路徑的長度。卷積層通常比遞歸層更昂貴,由K的可分離卷積〔6〕,但是,大大降低了復雜度,達到O(k·n·d+n·d2)。然而,即使具有k= n,可分離卷積的復雜性等于自關注層和點前饋層的組合,我們在模型中采用的方法。 |
| As side benefit, self-attention could yield more interpretable models. We inspect attention distributions from our models and present and discuss examples in the appendix. Not only do individual attention heads clearly learn to perform different tasks, many appear to exhibit behavior related to the syntactic and semantic structure of the sentences. | 作為附帶好處,self-attention可以產生更多可解釋的模型。我們從我們的模型中檢查注意分布,并在附錄中給出和討論示例。不僅個體的注意頭清楚地學會了執行不同的任務,許多似乎表現出與句子的句法和語義結構有關的行為。 |
5、Training
| This section describes the training regime for our models. | 本節介紹我們的模型的訓練制度。 |
5.1、Training Data and Batching
| We trained on the standard WMT 2014 English-German dataset consisting of about 4.5 million sentence pairs. Sentences were encoded using byte-pair encoding [3], which has a shared source- target vocabulary of about 37000 tokens. For English-French, we used the significantly larger WMT 2014 English-French dataset consisting of 36M sentences and split tokens into a 32000 word-piece vocabulary [38]. Sentence pairs were batched together by approximate sequence length. Each training batch contained a set of sentence pairs containing approximately 25000 source tokens and 25000 target tokens. | 我們使用標準的WMT 2014英德數據集進行訓練,該數據集由大約450萬個句子對組成。句子使用字節對編碼[3]進行編碼,它有一個大約37000個標記的共享源-目標詞匯表。 對于英語-法語,我們使用了更大的WMT 2014英語-法語數據集,該數據集包含3600萬個句子,并將標記拆分為32000個詞條詞匯[38]。句子對由近似的序列長度組合在一起。每個訓練批次包含一組句子對,其中包含大約25000個源令牌和25000個目標令牌。 |
5.2、Hardware and Schedule—8臺+12小時/3.5天
| We trained our models on one machine with 8 NVIDIA P100 GPUs. For our base models using the hyperparameters described throughout the paper, each training step took about 0.4 seconds. We trained the base models for a total of 100,000 steps or 12 hours. For our big models,(described on the bottom line of table 3), step time was 1.0 seconds. The big models were trained for 300,000 steps (3.5 days). | 我們用8臺NVIDIA P100 gpu在一臺機器上訓練我們的模型。對于使用本文描述的超參數的基礎模型,每個訓練步驟大約需要0.4秒。我們對基礎模型進行了總共100000步或12小時的訓練。對于我們的大型模型(見表3的底線),步進時間為1.0秒。大模型接受了30萬步(3.5天)的訓練。 |
5.3、Optimizer—Adam優化器
| We used the Adam optimizer [20] with β1 = 0.9, β2 = 0.98 and E = 10?9. We varied the learning rate over the course of training, according to the formula: | 我們使用Adam優化器[20],beta1=0.9,beta2=0.98,E=10-9。我們在整個訓練過程中根據以下公式調整學習率: |
| This corresponds to increasing the learning rate linearly for the first warmup_steps training steps,and decreasing it thereafter proportionally to the inverse square root of the step number. We used warmup_steps = 4000. | 這相當于線性地增加第一個warmup_steps 的學習率,然后與步驟數的平方根成比例地降低學習率。我們采用了warmup_steps =4000。 |
5.4、Regularization?—3種正則化
We employ three types of regularization during training:
| 在訓練期間,我們采用3種正則化:
|
| Table 2: The Transformer achieves better BLEU scores than previous state-of-the-art models on the English-to-German and English-to-French newstest2014 tests at a fraction of the training cost.
| 表2:Transformer在英語到德語和英語到法語的newstest2014測試中取得了比以前最先進的模式更好的BLEU分數,只需花費很少的訓練成本。 在訓練中,我們使用Els = 0.1[36]的值進行標簽平滑。這傷害了perplexity,因為模型學會了更不確定,但提高了準確性和BLEU分數。 |
6、Results
6.1、Machine Translation
| On the WMT 2014 English-to-German translation task, the big transformer model (Transformer (big) in Table 2) outperforms the best previously reported models (including ensembles) by more than 2.0 BLEU, establishing a new state-of-the-art BLEU score of 28.4. The configuration of this model is listed in the bottom line of Table 3. Training took 3.5 days on 8 P100 GPUs. Even our base model surpasses all previously published models and ensembles, at a fraction of the training cost of any of the competitive models. On the WMT 2014 English-to-French translation task, our big model achieves a BLEU score of 41.0, outperforming all of the previously published single models, at less than 1/4 the training cost of the previous state-of-the-art model. The Transformer (big) model trained for English-to-French used dropout rate Pdrop = 0.1, instead of 0.3. | 在WMT 2014英德翻譯任務中,big transformer模型(表2中的transformer(big))比之前報告的最佳模型(包括集成)的表現超過2.0 BLEU,新的最新BLEU分數為28.4。此型號的配置列于表3的最后一行。訓練時間為3.5天,平均成績為8 P100。即使是我們的基礎模型也超過了所有之前發布的模型和集合,只是任何競爭模型的訓練成本的一小部分。 在WMT 2014英法翻譯任務中,我們的大模型達到了41.0的BLEU分數,超過了所有之前發布的單一模型,在不到1/4的訓練成本的前一個最先進的模式。為英語到法語培訓的Transformer(big)模型使用的是輟學率Pdrop=0.1,而不是0.3。 |
| For the base models, we used a single model obtained by averaging the last 5 checkpoints, which were written at 10-minute intervals. For the big models, we averaged the last 20 checkpoints. We used beam search with a beam size of 4 and length penalty α = 0.6 [38]. These hyperparameters were chosen after experimentation on the development set. We set the maximum output length during inference to input length + 50, but terminate early when possible [38]. | 對于基本模型,我們使用一個通過平均最后5個檢查點(以10分鐘為間隔寫入)獲得的模型。對于大型模型,我們平均使用了最后20個檢查點。我們使用波束搜索,波束大小為4,長度懲罰α=0.6[38]。這些超參數是在開發集上進行實驗后選擇的。在輸入長度為50時,我們設定最大輸出長度,但在可能時終止(38)。 ? |
| Table 2 summarizes our results and compares our translation quality and training costs to other model architectures from the literature. We estimate the number of floating point operations used to train a model by multiplying the training time, the number of GPUs used, and an estimate of the sustained single-precision floating-point capacity of each GPU 5. | 表2總結了我們的結果,并將我們的翻譯質量和訓練成本與文獻中的其他模型架構進行了比較。我們通過乘以訓練時間、使用的GPU數量和每個GPU 5的持續單精度浮點容量,來估計用于訓練模型的浮點操作的數量。 |
6.2、Model Variations
| To evaluate the importance of different components of the Transformer, we varied our base model in different ways, measuring the change in performance on English-to-German translation on the development set, newstest2013. We used beam search as described in the previous section, but no checkpoint averaging. We present these results in Table 3. | 為了評估Transformer不同部件的重要性,我們以不同的方式改變了我們的基本模型,測量了開發集newstest2013中英德語翻譯的性能變化。我們使用前一節中描述的波束搜索,但沒有檢查點平均。這些結果見表3。 |
Table 4: The Transformer generalizes well to English constituency parsing (Results are on Section 23 of WSJ)
表4:Transformer很好地概括了英語選民解析(結果見《華爾街日報》第23章)
In Table 3 rows (A), we vary the number of attention heads and the attention key and value dimensions, keeping the amount of computation constant, as described in Section 3.2.2. While single-head attention is 0.9 BLEU worse than the best setting, quality also drops off with too many heads.
在表3行(A)中,我們改變了注意頭的數量、注意鍵和值維度,保持計算量不變,如3.2.2節所述。單頭注意力比最佳設置差0.9個BLEU,但如果頭太多,質量也會下降。
6.3、English Constituency Parsing
| To evaluate if the Transformer can generalize to other tasks we performed experiments on English constituency parsing. This task presents specific challenges: the output is subject to strong structural constraints and is significantly longer than the input. Furthermore, RNN sequence-to-sequence models have not been able to attain state-of-the-art results in small-data regimes [37]. | 為了評估轉換程序是否可以推廣到其他任務,我們進行了英語選區解析的實驗。這項任務提出了具體的挑戰:產出受到強烈的結構限制,而且明顯長于投入。此外,RNN序列到序列模型無法在小數據區獲得最新的結果[37]。 ? |
| We trained a 4-layer transformer with dmodel = 1024 on the Wall Street Journal (WSJ) portion of the Penn Treebank [25], about 40K training sentences. We also trained it in a semi-supervised setting, using the larger high-confidence and BerkleyParser corpora from with approximately 17M sentences [37]. We used a vocabulary of 16K tokens for the WSJ only setting and a vocabulary of 32K tokens for the semi-supervised setting. | 我們在《華爾街日報》(Wall Street Journal)的Penn Treebank[25]部分訓練了一個dmodel=1024的4層transformer ,大約4萬個訓練句子。我們還訓練了它在半監督設置,使用較大的高置信度和BerkleyParser語料庫從大約17M句[37 ]。我們只對WSJ設置使用了16K令牌的詞匯表,對半監督設置使用了32K令牌的詞匯表。 ? |
| We performed only a small number of experiments to select the dropout, both attention and residual (section 5.4), learning rates and beam size on the Section 22 development set, all other parameters remained unchanged from the English-to-German base translation model. During inference, we increased the maximum output length to input length + 300. We used a beam size of 21 and α = 0.3 for both WSJ only and the semi-supervised setting. | 我們只進行了少量的實驗來選擇22段開發集上的dropout、attention 和residual (第5.4節)、學習率和beam 大小,所有其他參數從英語到德語的基礎翻譯模型保持不變。在推理過程中,我們將最大輸出長度增加到輸入長度+ 300。我們使用21和α=0.3的光束尺寸,僅用于WSJ和半監督設置。 ? |
| Our results in Table 4 show that despite the lack of task-specific tuning our model performs sur- prisingly well, yielding better results than all previously reported models with the exception of the Recurrent Neural Network Grammar [8]. In contrast to RNN sequence-to-sequence models [37], the Transformer outperforms the Berkeley- Parser [29] even when training only on the WSJ training set of 40K sentences. | 我們在表4中的結果表明,盡管缺乏特定于任務的調整,我們的模型仍然運行得很好,產生的結果比以前報告的所有模型都要好,除了遞歸神經網絡語法[8]。 與RNN的序列到序列模型[37]相比,Transformer甚至在僅接受華爾街日報的40K句子訓練集訓練時,也比Berkeley- Parser[29]表現更好。 |
7、Conclusion
| In this work, we presented the Transformer, the first sequence transduction model based entirely on attention, replacing the recurrent layers most commonly used in encoder-decoder architectures with multi-headed self-attention. | 在這項工作中,我們提出了第一個完全基于注意的序列轉換模型Transformer,它用多頭self-attention取代了編碼器-解碼器架構中最常用的遞歸層。 ? |
| For translation tasks, the Transformer can be trained significantly faster than architectures based on recurrent or convolutional layers. On both WMT 2014 English-to-German and WMT 2014 English-to-French translation tasks, we achieve a new state of the art. In the former task our best model outperforms even all previously reported ensembles. | 對于轉換任務,可以比基于遞歸層或卷積層的體系結構更快地訓練Transformer 。在WMT 2014英語-德語和WMT 2014英語-法語翻譯任務中,我們達到了一個新的水平。在前一個任務中,我們的最佳模型甚至優于所有先前報告的集成模型。 ? |
| We are excited about the future of attention-based models and plan to apply them to other tasks. We plan to extend the Transformer to problems involving input and output modalities other than text and to investigate local, restricted attention mechanisms to efficiently handle large inputs and outputs such as images, audio and video. Making generation less sequential is another research goals of ours. | 我們對基于注意力的模型的未來感到興奮,并計劃將其應用到其他任務中。我們計劃將轉換器擴展到涉及文本以外的輸入和輸出模式的問題,并研究局部的、受限的注意機制,以有效地處理圖像、音頻和視頻等大型輸入和輸出。減少世代的連續性是我們的另一個研究目標。 ? |
| The code we used to train and evaluate our models is available at https://github.com/ tensorflow/tensor2tensor. Acknowledgements We are grateful to Nal Kalchbrenner and Stephan Gouws for their fruitful comments, corrections and inspiration. | 我們用來訓練和評估模型的代碼可以在https://github.com/tensorflow/tensor2tensor上找到。感謝Nal Kalchbrenner和Stephan Gouws的富有成效的評論、更正和啟發。 |
References
[1] Jimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization.?arXiv preprint?arXiv:1607.06450, 2016.
[2] Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. Neural machine translation by jointly learning to align and translate.?CoRR, abs/1409.0473, 2014.
[3] Denny Britz, Anna Goldie, Minh-Thang Luong, and Quoc V. Le. Massive exploration of neural machine translation architectures.?CoRR, abs/1703.03906, 2017.
[4] Jianpeng Cheng, Li Dong, and Mirella Lapata. Long short-term memory-networks for machine reading.?arXiv preprint?arXiv:1601.06733, 2016.
[5] Kyunghyun Cho, Bart van Merrienboer, Caglar Gulcehre, Fethi Bougares, Holger Schwenk, and Yoshua Bengio. Learning phrase representations using rnn encoder-decoder for statistical machine translation.?CoRR, abs/1406.1078, 2014.
[6] Francois Chollet. Xception: Deep learning with depthwise separable convolutions.?arXiv preprint?arXiv:1610.02357, 2016.
[7] Junyoung Chung, ?aglar Gül?ehre, Kyunghyun Cho, and Yoshua Bengio. Empirical evaluation of gated recurrent neural networks on sequence modeling.?CoRR, abs/1412.3555, 2014.
[8] Chris Dyer, Adhiguna Kuncoro, Miguel Ballesteros, and Noah A. Smith. Recurrent neural network grammars. In?Proc. of NAACL, 2016.
[9] Jonas Gehring, Michael Auli, David Grangier, Denis Yarats, and Yann N. Dauphin. Convolu- tional sequence to sequence learning.?arXiv preprint?arXiv:1705.03122v2, 2017.
[10] Alex Graves. Generating sequences with recurrent neural networks.?arXiv preprint?arXiv:1308.0850, 2013.
[11] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for im- age recognition. In?Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 770–778, 2016.
[12] Sepp Hochreiter, Yoshua Bengio, Paolo Frasconi, and Jürgen Schmidhuber. Gradient flow in recurrent nets: the difficulty of learning long-term dependencies, 2001.
[13] Sepp Hochreiter and Jürgen Schmidhuber. Long short-term memory.?Neural computation, 9(8):1735–1780, 1997.
[14] Zhongqiang Huang and Mary Harper. Self-training PCFG grammars with latent annotations across languages. In?Proceedings of the 2009 Conference on Empirical Methods in Natural Language Processing, pages 832–841. ACL, August 2009.
[15] Rafal Jozefowicz, Oriol Vinyals, Mike Schuster, Noam Shazeer, and Yonghui Wu. Exploring the limits of language modeling.?arXiv preprint?arXiv:1602.02410, 2016.
[16] ?ukasz Kaiser and Samy Bengio. Can active memory replace attention? In?Advances in Neural Information Processing Systems, (NIPS), 2016.
[17] ?ukasz Kaiser and Ilya Sutskever. Neural GPUs learn algorithms. In?International Conference on Learning Representations (ICLR), 2016.
[18] Nal Kalchbrenner, Lasse Espeholt, Karen Simonyan, Aaron van den Oord, Alex Graves, and Ko- ray Kavukcuoglu. Neural machine translation in linear time.?arXiv preprint?arXiv:1610.10099v2, 2017.
[19] Yoon Kim, Carl Denton, Luong Hoang, and Alexander M. Rush. Structured attention networks.
In?International Conference on Learning Representations, 2017.
[20] Diederik Kingma and Jimmy Ba. Adam: A method for stochastic optimization. In?ICLR, 2015. [21] Oleksii Kuchaiev and Boris Ginsburg. Factorization tricks for LSTM networks.?arXiv preprint??arXiv:1703.10722, 2017.
[22] Zhouhan Lin, Minwei Feng, Cicero Nogueira dos Santos, Mo Yu, Bing Xiang, Bowen Zhou, and Yoshua Bengio. A structured self-attentive sentence embedding.?arXiv preprint?arXiv:1703.03130, 2017.
[23] Minh-Thang Luong, Quoc V. Le, Ilya Sutskever, Oriol Vinyals, and Lukasz Kaiser. Multi-task sequence to sequence learning.?arXiv preprint?arXiv:1511.06114, 2015.
[24] Minh-Thang Luong, Hieu Pham, and Christopher D Manning. Effective approaches to attention- based neural machine translation.?arXiv preprint?arXiv:1508.04025, 2015.
[25] Mitchell P Marcus, Mary Ann Marcinkiewicz, and Beatrice Santorini. Building a large annotated corpus of english: The penn treebank.?Computational linguistics, 19(2):313–330, 1993.
[26] David McClosky, Eugene Charniak, and Mark Johnson. Effective self-training for parsing. In?Proceedings of the Human Language Technology Conference of the NAACL, Main Conference, pages 152–159. ACL, June 2006.
[27] Ankur Parikh, Oscar T?ckstr?m, Dipanjan Das, and Jakob Uszkoreit. A decomposable attention model. In?Empirical Methods in Natural Language Processing, 2016.
[28] Romain Paulus, Caiming Xiong, and Richard Socher. A deep reinforced model for abstractive summarization.?arXiv preprint?arXiv:1705.04304, 2017.
[29] Slav Petrov, Leon Barrett, Romain Thibaux, and Dan Klein. Learning accurate, compact, and interpretable tree annotation. In?Proceedings of the 21st International Conference on Computational Linguistics and 44th Annual Meeting of the ACL, pages 433–440. ACL, July 2006.
[30] Ofir Press and Lior Wolf. Using the output embedding to improve language models.?arXiv preprint?arXiv:1608.05859, 2016.
[31] Rico Sennrich, Barry Haddow, and Alexandra Birch. Neural machine translation of rare words with subword units.?arXiv preprint?arXiv:1508.07909, 2015.
[32] Noam Shazeer, Azalia Mirhoseini, Krzysztof Maziarz, Andy Davis, Quoc Le, Geoffrey Hinton, and Jeff Dean. Outrageously large neural networks: The sparsely-gated mixture-of-experts layer.?arXiv preprint?arXiv:1701.06538, 2017.
[33] Nitish Srivastava, Geoffrey E Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdi- nov. Dropout: a simple way to prevent neural networks from overfitting.?Journal of Machine Learning Research, 15(1):1929–1958, 2014.
[34] Sainbayar Sukhbaatar, Arthur Szlam, Jason Weston, and Rob Fergus. End-to-end memory networks. In C. Cortes, N. D. Lawrence, D. D. Lee, M. Sugiyama, and R. Garnett, editors,?Advances in Neural Information Processing Systems 28, pages 2440–2448. Curran Associates, Inc., 2015.
[35] Ilya Sutskever, Oriol Vinyals, and Quoc VV Le. Sequence to sequence learning with neural networks. In?Advances in Neural Information Processing Systems, pages 3104–3112, 2014.
[36] Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, and Zbigniew Wojna.?Rethinking the inception architecture for computer vision.?CoRR, abs/1512.00567, 2015.
[37] Vinyals & Kaiser, Koo, Petrov, Sutskever, and Hinton. Grammar as a foreign language. In?Advances in Neural Information Processing Systems, 2015.
[38] Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V Le, Mohammad Norouzi, Wolfgang Macherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, et al. Google’s neural machine translation system: Bridging the gap between human and machine translation.?arXiv preprint?arXiv:1609.08144, 2016.
[39] Jie Zhou, Ying Cao, Xuguang Wang, Peng Li, and Wei Xu. Deep recurrent models with fast-forward connections for neural machine translation.?CoRR, abs/1606.04199, 2016.
[40] Muhua Zhu, Yue Zhang, Wenliang Chen, Min Zhang, and Jingbo Zhu. Fast and accurate shift-reduce constituent parsing. In?Proceedings of the 51st Annual Meeting of the ACL (Volume 1: Long Papers), pages 434–443. ACL, August 2013.
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Paper:2017年的Google机器翻译团队《Transformer:Attention Is All You Need》翻译并解读的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 成功解决TypeError: Scala
- 下一篇: DL之Yolov3:基于深度学习Yolo