https://arxiv.org/abs/1706.03762

 

Attention Is All You Need

The dominant sequence transduction models are based on complex recurrent or convolutional neural networks in an encoder-decoder configuration. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new

arxiv.org

Abstract

기존의 Dominant Sequence Transduction Model들은 인코더 디코더를 포함하는 복잡한 Recurrent 또는 CNN 기반
가장 성능이 좋은 모델 또한 Attention 메커니즘을 통해 인코더와 디코더를 연결
저자들은 Recurrence와 Convolution을 완전히 배제한 새로운 Network인 Transformer를 제안
두 개의 Translation Task에서 모델이 우수하고 병렬화되어 훈련시간이 훨씬 적게 소요된다는 것을 보여줌
영어-독일어 번역 작업에서 최고 성능은 물론이고, 영어-프랑스어 번역에서도 8개의 GPU를 이용하여 3.5일간 학습 후 Sota에 달성(기존보다 작은 Training Cost)

1. Introdutction

RNN, LSTM, GRU Network는 Sequence Modeling, Machine Translation 등 분야에서 많이 이용

Recurrent Language Model과 Encoder-Decoder의 Boundary를 넓히기 위해 노력

Recurrent Model을 일반적으로 입력 및 출력 시퀀스에 따라 계산을 진행

단계 별로 계산을 진행하므로 이전 Hidden State Ht-1과 t 순서의 입력이 있어야 함

이런 방식은 순차적 특성으로 인해서 Training 시에 병렬처리에 한계가 존재하고, 메모리 제약으로 인해 더 긴 Sequence Length에서 중요해짐

최근 연구에서는 Factorization Trick,  Conditional Computation을 통해 계산 효율을 높이고, 모델 성능을 높임

하지만 Sequential Computation은 근본적인 제약이 있어 한계가 있음

 

Attention Mechanisms은 Sequence Modeling 및 Transduction Model의 다양한 부분에서 필수적인 부분이 되어고, Input Output Sequence Distance에 상관없이 Dependencies를 모델링 할 수 있음

몇 가지 특별한 경우를 제외하고 Attention은 Recurrent Network와 같이 사용됨

 

논문의 저자들은 Recurrence를 피하는 대신 Attention에 전적으로 의존하여 입력과 출력 사이에  Global Dependencies를 도출하는 모델인 Transformer를 제안

모델 병렬화에 큰 효과가 있어 P100 GPU를 이용하여 번역 품질을 개선

2. Background

Sequential Compuation을 줄이기 위해 ByteNet, ConvS2S는 Convolution Neural Network를 기본으로 이용하여 모든 입력과 출력 위치에 대해 hidden representation을 병렬화 (RNN을 CNN으로 표현한 연구)

CNN의 경우 n개의 단어를 문맥으로 파악하려면 드는 시간은 O(n/k)이다. RNN의 경우를 생각해보면 linear하기 때문에 시간은 O(n)

이런 모델들은 Input, Output 위치의 신호를 연관시키는데 필요한 작업수가 많이 늘어나 서로간의 Dependencies를 학습하는게 어려움

Transformer는 이러한 작업의 수를 Constant로 줄여주는 Multi Head Attention을 이용

 

Self-Attention은 Sequence의 Representation을 계산하기 위해서 Single Sequence내에서 다른 위치와 연관된 Attention

Self-Attention은 다양한 Task에서 성공적으로 이용

 

End-To-End Memory network는 Sequence-Aligned Recurrence 대신에 Recurrent Attenton Mechanism을 기반으로 하고, QA 및 모델링에서 우수한 성능을 발휘 (Recurrent방식이 Sequence방식보다 좋은성능을 보임)

 

Transformer는 Self-attention에만 의존한 최초의 Transduction Model

3. Model Architecture

가장 Competitive Neural Sequence Transduction Model은 Encoder-Decoder 형태

Encoder의 경우 Input으로 (x1, ..., xn)을 받아 representations z = (z1, ..., zn), 정보가 담겨있는 z를 생성

Decoder의 경우 z를 입력 받아  (y1, ..., ym)를 생성

각 Step마다 Model을 Auto-regressive하고 동작한다. 즉 Decoder의 출력이 다시 입력으로 들어감

 

Transformer는 figure1의 왼쪽 및 오른쪽 절반은 각각 Encoder와 Decoder가 쌓여있는 모양

self-attention과 point-wise fully connected layer를 이용하여 전체적인 아키텍처가 완성

3.1 Encoder and Decoder Stacks

Encoder

Encoder는 6개의 같은 Layer가 쌓여있는 모양

각 Layer는 2개의 Sub-Layer를 가짐(Multi-Head Self-Attention, Position-wise fc layer)

각각의 Sub-layer에 Residual-Connection을 추가

그 뒤에 Layer Normalization을 진행 그러므로 각각의 Sub-Layer는 LayerNorm(x + Sublayer(x))

Residual-Connection으로 인해 Input Output의 차원은 dmodel=512로 유지

Decoder

Decoder또한 6개의 같은 Layer가 쌓여있는 모양

각 Layer는 Encoder Layer와 유사하나 Masked-Multi Head Attention이 추가됨

Residual Connection을 추가하고, Layer Normalization을 진행

Masked-Multi Head Attention을 통해 i위치에 대한 Prediction이 i보다 앞에있는, 즉 이전의 출력에 대해 Attention을 구할 수 있음

3.2 Attention

Attention 함수는 Query, key, value, output들이 모두 Vector일 때 ,Query와 key-Value 쌍의 집합을 매핑하는 것으로 설명이 가능
Output은 Value Weight Sum로 게산되며, 여기서 각 Value 값에 할당된 Weight들은 key와 Query의 Compatibility function 에 의해 계산

3.2.1 Scaled Dot-Product Attention

'Scaled Dot-Product Attention'은 위와 같다

input으로 들어오는 Query와 Key의 dimension은 dk이고, Value의 Dimension은 dv

Attention이 궁금한 단어의 Query와 모든 단어의 Key와 Dot-Product를 취하고 루트dk로 나눠준 뒤에 Softmax를 통해 Value에 곱해지는 Weight를 생성, 그 뒤에 Weighted Sum으로 해당 단어와 모든 단어의 Attention을 생성

 

계산법에는 Additive Attention과 Dot-Product Attention이 존재

Additive Attention의 경우 Single Layer를 통해 Feed Forward로 compatibility function을 계산,

Dot-Product는 dk를 나눠주는것을 제외하면 동일

일반적으로 dk가 작으면 비슷한 성능을 보여주지만, dk가 커질 경우에 softmax에 의해 gradient가 작아지는 문제가 존재하므로 Additive가 좋지만, 해당 논문에서는 dk를 이용해 Scaling ( 기본적으로 Dot-Product는 연산이 매우 가벼움)

3.2.2 Multi-Head Attention

d-model dimension인 Query, Key, Value로 single attention을 취하는 것보다 h개의 다른 Linear Projection을 취하는 것이 효과적
Multi Head를 통해 모델은 서로 다른 위치에서 서로 다른 Subspace의 Attention을 취함

만약 h = 8 인 경우 dk = dv = dmodel / h = 64로 하여 Single Head Attention과 동일한 연산량을 유지

3.2.3 Applications of Attention in our Model

Transformer는 3가지의 다른 방식으로 Multi-Head Attention을 사용

 

'Encoder - Decoder Attention' 에서 Query는 이전 Decoder Layer의 출력, Key와 Value는  Encoder의 Output
이를 통해서 Decoder는 Input Sequence의 모든 Position에 대해 Attend가능

Sequence To Sequence Model에서 일반적인 Encoder-Decoder Attention을 모방

 

Encoder에는 Self-Attention Layer가 포함됨

Self-Attention Layer의 Query, Key, Value는 같은 장소에서 옴

이 경우 Encoder의 이전 Layer의 Output

Encoder의 각 Position은 Encoder의 이전 Layer의 모든 Position에 관여 가능

 

비슷하게 Decoder또한 Self-Attention Layer를 가짐

Decoder의 Self-Attention 또한 Decoder의 모든 Position에 Attention이 가능

이때 Auto-Regressive한 특성으로 인해 Decoder는 아직 예측하지 못한부분을 Attention하지 못하기 때문에 Masked Self-Attention 진행

3.3 Position-wise Feed-Forward Networks

Attention Sub-Layer이외에도 Encoder와 Decoder의 각 Layer는 Fully Connected Feed Forward Network가 포함

이 Network는 Activation Function으로 ReLU를 이용하며 W1, W2를 이용해 Linear Transformation을 진행

Input 및 Output Dimension은 dmodel = 512 이고, 내부 Dimension은 dff = 2048

3.4 Embeddings and Softmax

Embedding 같은 경우 다른 Sequence Transduction Model과 비슷하게진행

Input Token과 Output Token을 차원을 dmodel로 변환하기 위해 Training된 Embedding을 이용

그리고 일반적으로 Training된 Linear -Transfomation과 Softmax를 이용하여 구한 Decoder의 출력을 Token 확률로 변환

3.5 Positional Encoding

Transformer는 Recurrence와 Convolution도 이용하지 않음, Model이 Sequence를 사용하기 이해 Token의 상대적 또는 절대적 위치에 대한 정보가 필요

이를 위해 Encoder-Decoder Stack 하단 Input Embedding에 Positional Encoding을 추가

Positional Encoding과 Embedding은 같은 차원인 dmodel을 가짐(합치기 가능)

해당 작업에 서로 다른 freq를 가지 sin과 cos을 이용

 

Pos : Position

i: Token Vector의 차원

Transformer는 Sine을 이용하는데, Model이 더 긴 Sequence 길이를 추론 가능

4. Why Self-Attention

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.

해당 Section 에서는 Self-Attention과 Convolution, Recurrent Layer와 비교

3가지를 고려하는데 Computational Complexity Per Layer, Computational Can Parallelized, Long-Range Dependencies 길이

 

3번째 같은 경우에는 Long-Range Dependencies 사이의 Path 길이
Long-Range Dependency 속성을 하는 것은 Sequence Transduction Task의 핵심

이런 Dependencies를 학습하는 능력에 가장 큰 영향을 미치는 것은 forward, backward path의 길이

input 및 output Sequence의 위치가 서로 가까울수록 Dependencies를 학습하기 쉬움

그러므로 Input과 Output Position을 비교

 

Table1을 보면 Self-Attention Layer는 모든 Position을 Constant Number로 연결함

하지만 Recurrent Layer 같은 경우 O(n)이 소요

Computational Complexity 관점에서 n이 d보다 작을 경우에  Self Attention 은 Recurrent보다 낮음, 일반적으로 n<d해당

만약 매우 긴 Sequence를 가진 작업에 대해서 성능을 향상시키기 위해 각 input Sequece의 neighborhood size를 r로 제한

이는 maximum path의 길이를 O(n/r)로 증가시킴, 저자들의 Future Work

 

k < n인 Single Conv Layer는 input과 output의 모든 Pair를 연결 x

Contiguous Kernel의 경우 O(n/k)의 Convolution Stack이 필요

Dilated Convolution의 경우 O(logk(n))이 필요, 계산랑 증가

Convolution Layer는 일반적으로 Recurrent Layer보다 k배 비쌈

근데 Seperable Convolution을 이용하면  

추가적으로 문장의 구조적, 의미적 구조를 잘 연관시킨다

또한 Model이 해석이 가능하고, Attention Map을 시각화하여 왜 이런 결과가 나오는지 해석 가능

+ Recent posts