이전 포스트에서 다룬 Attention Mechanism 의 개념을 바탕으로 Transformer에 대해 학습해본다. Transformer와 관련된 논문 "Attention Is All You Need"를 리뷰한다.
1. Transformer
2. 논문 리뷰
1. Transformer
- 구글이 2017년에 발표한 "Attention is all you need" 논문에서 제안된 모델 - GPT와 같은 대규모 언어모델의 기반이 되고 있음 - 자연어처리 뿐만 아니라 컴퓨터 비전이나 음성 인식 등 다른 분야에도 활용되어 AI의 성능을 향상
1) Transformer 등장 배경
- 이전까지는 RNN 혹은 CNN 기반의 encoder-decoder 모델은 sequence를 순차적으로 처리 - 이로 인해 sequence 길이가 길어질수록 연산량이 증가하고 병렬화가 어렵다는 문제 발생 - 또한 거리가 먼 단어 간 관계를 제대로 해석하지 못하는 정보 소실 문제 발생
➡️ Transformer = recurrence 혹은 convolution을 사용하지 않고 attention mechanism을 전적으로 사용하는 모델 = input과 output sequence의 모든 요소들 사이의 attentinon을 병렬적으로 계산함으로써 학습 속도는 빠르면서도 문맥을 더 정확하게 이해하는 높은 성능의 번역을 가능하게 만듬
==> attention mechanism만을 사용하여 input과 output의 모든 요소 간 전역 의존성(global dependencies)을 병렬적으로 모델링함으로써 대규모 데이터셋을 빠르게 학습하고 높은 성능을 발휘하는 모델
→ linear transformation → softmax → output probabilities
d_model = 512 : 모델의 차원 = encoder와 decoder에서 입출력의 크기 = 임베딩 벡터의 크기
d_q = d_k = d_v = d_model / num_head = attention에서 Q, K, V의 크기
num_layers = 6 : encoder와 decoder의 layer 개수
num_head = h =8 : attention layer에서 병렬 계산을 수행하는 head의 개수
d_ff = 2048 : feed forward network 은닉층의 layer 개수
출처 : https://wikidocs.net/31379
Encoder
- 6개의 encoder layers, 각 encoder마다 2개의 sub-layers - multi-head self-attention mechanism + position-wise fully connected feed-forward network
Decoder
- 6개의 decoder layers, 각 decoder마다 3개의 sub-layers - masked multi-head self-attention mechanism + multi-head attention mechanism + position-wise fully connected feed-forward network
positional encoding
- positional encoding = embedding vector에 더해지는 위치 정보 - Transformer는 sequence를 순차적으로 입력받지 않기 때문에 embedding vector가 입력되기 전 위치 정보인 positional encoding을 추가하는 과정이 필요 - 같은 단어라 embedding vector가 같더라도 positional encoding 값이 더해짐으로써 위치에 따라 Transformer로 들어가는 입력값은 달라짐
- positional encoding 값
pos : input sentence에서 단어의 position
i : embedding vector에서 단어의 dimension
- 위치 정보가 반영된 입력값 = embedding vector matrix + positional encoding matrix
※ Positional Encoding에 왜 sin, cos 함수를 사용하는 이유? - 미분 가능한 함수로 모델의 학습에 유리 - 삼각함수의 덧셈정리 → 토큰 간 위치관계를 계산하는 것이 용의 + sin/cos값을 embedding matrix에서 분리하기 쉬움 - 모든 값이 -1 ~ 1 사이에 위치 → 위치가 초반 혹은 후반에 갈수록 positional encoding 값이 커지거나 작아지는 것을 막을 수 있음 + 단어의 의미를 변질시킬 정도로 word embedding 값에 영향을 주지 않음
출처 : https://velog.io/@gibonki77/DLmathPE
- sin/cos 함수식에서 i는 i=1~i=’embedding vector의 차원’ 값을 가짐, i값을 다르게 해서 sin/cos 함수의 주기를 다르게 설정함으로써 서로 다른 위치 간 position encoding의 값에서 차이를 만들어냄. 위치별로 -1~1 사이의 값을 다양하게 가질 수 있음 → 문장이 길어져도 위치 벡터값의 차이가 명확하게 나타날 수 있도록 해줌 - (참고 링크) https://www.blossominkyung.com/deeplearning/transfomer-positional-encoding#37c2b888-b613-477e-9053-31a4cf2d3e67
Multi-head self Attention
Query : 질문할 단어
Key : Query와 관계를 알아볼 단어 벡터
Value: Key 단어의 실제 값
W_Q : 입력 벡터를 Query 벡터로 변환하는 가중치 행렬 각 단어가 다른 단어들과 어떤 관계를 가지는지 학습
W_K : 입력 벡터를 Key 벡터로 변환하는 가중치 행렬 각 단어가 어떤 정보와 연결되어 있는지 학습
W_V : 입력 벡터를 Value 벡터로 변환하는 가중치 행렬 각 단어가 실제로 가지고 있는 정보를 학습
① Self-attention
- Q, K, V가 모두 동일한 attention
- Transformer는 Q, K, V가 각각 input / output sequence에 있는 단어들로 동일한 self-attention 이용 sequence 내 단어들끼리 유사도를 구함으로써 단어들 간 연관성을 파악
* Cross Attention : self attention이 같은 sequence 내에서 토큰들 간의 관계를 보는 것이라면, cross attention은 이와 반대로 서로 다른 sequence 간 토큰들의 관계를 봄
- 모든 단어에 대해서 d_q, d_k, d_v 크기의 Q, K, V 벡터를 계산해 Q, K, V matrix 생성
→ 구한 Q, K, V matrix로 scaled dot-product attention matrix를 생성 = 각 단어가 문장 내 다른 단어들과 얼마나 유사한지 연관성을 나타내는 attention matrix 생성
- 위와 같이 행렬 연산을 사용해 모든 단어의 self-attention 값을 일괄적으로 처리
② Multi-head Attention
- attention을 1번만 구하는 것이 아니라 여러번 병렬적으로 계산하는 방식
출처 : https://wikidocs.net/31379
- head = attention value matrix
- d_model(=512)을 num_heads(=h=8)개로 나눈 크기d_k(=64)만큼의 차원을 가지는
Q, K, V로 attention을 구하는 과정을 h번 병렬적으로 수행
→병렬적으로 수행한 head를 모두 연결하여 concatenated matrix 생성
→가중치 행렬 W_0를 곱하여 Multi-head Attentiond의 최종 출력값 생성
- 가중치 행렬 W_q, W_k, W_v의 값이 8개의 head마다 다르기 때문에 같은 문장에 대해서도 서로 다른 attention matrix가 생성되어 다양한 정보를 수집할 수 있음
➡️ Transformer는 3종류의 attention layer를 가짐
Self-attention layer in encoder - encoder에 있는 attention layer - Self-attention+ Multi-Head-Attention - Q, V, K는 모두 input sequence의 단어들
Self-attention layer in decode - decoder에 있는 첫번째 attention layer - MaskedSelf-attention+ Multi-Head-Attention - Q, V, K는 모두 input sequence의 단어들이나 attention score matrix에 look-ahead mask 적용
encoder-decoder attention layer - decoder에 있는 두번째 attention layer - self-attention이 아닌 Multi-Head-Attention - Q는 decoder self-attention layer의 출력값, V와 K는 encoder의 출력값
※ look-ahead mask
: 다음 단어를 예측할 때 미래 state의 정보를 사용할 수 없으나 Transformer에서는 단어의 위치에 상관없이 attention을 구하게 된다. 따라서 현재보다 뒤에 나오는 단어들을 예측에 활용하지 못하도록 계산된 attention score matrix의 일부를 masking하는 과정이 추가된다.
출처 : https://wikidocs.net/31379
Position-wise Fully-connected FFNN
- encoder와 decoder의 attention layer 다음에 위치
- 매개변수 W_1, b_1, W_2, b_2는 각 FFNN마다 다른 값을 가짐
출처 : https://wikidocs.net/31379
Residual connection + Layer Normalization
출처 : https://wikidocs.net/31379
① Residual connection (잔차 연결) - layer의 입력값을 출력값에 더하는 역할 원래의 입력값을 유지하면서 layer를 통과하도록 유도 - 기울기 소실과 정보 소실을 막음으로써 학습의 안정성을 유지
② Layer Normalization (층 정규화) - layer 내의 모든 요소에 대해 평균과 분산을 계산하여 정규화 - 정규화를 통해 각 layer의 출력의 분포가 일정하게 유지되면서 학습의 안정성을 유지
2. 논문 리뷰
논문명 : Attention Is All You Need
저자명 : Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin
- Transformer 모델 고안 배경 : encoder-decoder 구조의 RNN과 CNN 기반 recurrent network model은 sequence의 위치를 따라 순차적으로 계산을 수행하기 때문에 길이가 긴 seqeunce를 학습시 병렬화가 어렵다는 한계
- Transformer 모델과 이전 모델의 차이점 " based solely on attention mechanisms, dispensing with recurrence and convolutions entirely " : recurrence와 convolution 없이 attention mechanism에만 전적으로 기반하는 모델
- Transformer의 구조 input/output embedding→ positional encoding → encoder/decoder로 입력 →(masked) multi-head attention → feed forward → encoder/decoder에서 출력 → linear transformation → softmax → output probabilities
③ Positional Encoding : reccurence와 convolution 사용하지 않는 대신 추가되는 작업 embedding vector에 sequence에서 토큰의 위치에 대한 정보를 주입
④ multi-head attention layer : 8개의 head를 이용한 Multi-Head Attention 각 head는 서로 다른 linear projection을 사용해 병렬적으로 Scaled Dot-Product Attention 계산 다양한 representation subspaces에서의 정보를 동시에 attention 가능
- 논문에서 보인 모델 특성 WMT 2014 English-to-German와 WMT 2014 English-to-French translation task에서 ① 기존의 sota보다 훨씬 적은 훈련 비용과 높은 병렬화 가능성을 보이면서도 ② 월등히 뛰어난 성능으로 새로운 sota BLEU 점수 달성
▶ 0. Abstract
- 기존의 sequence transduction 모델은 복잡한 RNN과 CNN의 encoder-decoder 구조 - recurrence와 convolution 없이 attention mechanism에만 기반하는 Transformer라는 새로운 모델을 제안 - WMT 2014 English-to-German와 WMT 2014 English-to-French translation tasks로 모델을 평가 - 실험 결과 모델 성능이 뛰어나면서도 병렬화가 더 잘 되고 학습 시간이 매우 짧았으며, 새로운 sota BLEU 점수를 달성함
- 이러한 recurrent network model들은 sequence의 위치를 따라 순차적으로 계산을 수행
t에서의 hidden state를 다음 t+1에서의 hidden state를 계산할 때 사용하는 형태
- 이러한 순차적인 계산 특성으로 인해 길이가 긴 seqeunce를 학습시 memory 제약으로 병렬화가 불가능하다는 한계가 존재
- attention mechanism은 input 또는 output sequence에서 거리와 관계없이 서로 간의 dependencies를 모델링할 수 있으나, 대부분의 sequence modeling에선 attention mechanism을 recurrent network와 함께 사용
*Sequence modeling : 어떠한 Sequence를 가지는 데이터로부터 또 다른 Sequence를 가지는 데이터를 생성하는 task
* Inductive learning - train data를 사용하여 함수를 학습하고, 함수를 이용해 test data를 예측하는 방식 - data에 숨겨진 패턴을 설명하는 함수(모델)을 학습
* Transduction - Inductive learning과 달리 함수를 학습하는 것이 아닌 train data에서 test data로 직접적으로 추론하는 방식 - test data 예측시 train data와의 유사성을 기반으로 판단
- MT는 어떠한 함수를 추론하는 것이 아니라 train data를 바탕으로 새로운 source language를 바로 target language로 변환 - 훈련 과정에서 입력과 출력을 관찰하며 source language의 문장 구조, 어휘, 문법 등의 특성이 target language를 생성에 미치는 영향을 파악 - 새로운 source language가 들어왔을때 train data에서 유사한 예를 찾아 적절한 번역 결과를 생성
- recurrence 없이 input과 output sequence 사이 전역 의존성(global dependencies)을 모델링
- Attention mechanism을 전적으로 사용하는 아키텍처
- 훨씬 더 많은 병렬화를 가능하게 하며, translation 과제에 있어 새로운 sota에 도달할 수 있음
▶ 2. Background
Extended Neural GPU, ByteNet, ConvS2S 등 CNN을 기반으로 하여 hidden stage를 병렬적으로 계산함으로써 계산량을 줄이려는 시도가 있었으나, 이 모델들도 input과 output position 간 거리가 증가할 수록 dependency를 학습하기 위한 계산량이 증가한다는 한계가 존재
➡️Transformer
- input과 output 간 dependency 학습을 상수시간 내에 완료할 수 있음
- RNN이나 CNN을 사용하지 않고, 전적으로 self-attention에만 사용하여 계산
* self-attention (intra-attention) : sequence representation을 계산하기 위해 하나의 sequence 내에서 서로 다른 위치에 있는 단어들 간 dependency를 계산하는 attention mechanism
* 이전 모델들은 RNN이나 CNN을 사용하는 encoder-decoder 구조의 recurrent model 순차적으로 계산하는 특성에 의해 input과 output 간 거리가 먼 경우 장기 의존성 문제 발생
▶ 3. Model Architecture
▶ 3.1 Encoder and Decoder Stacks
"using stacked self-attention and point-wise, fully connected layers" Encoder와 Decoder 모두 self-attention과 point-wise FC layer가 쌓인 구조를 사용
1) Encoder : - 6개의 동일한 layer가 쌓인 구조, 각 layer는 2개의 sub-layers로 구성
- masked multi-head self-attention은 output embedding이 입력값 이때 decoder의 경우 t state output을 만들 때 이전 state(t-1, t-2, ...)만을 참고해야 하기 때문에 attention을 계산할 때 masking을 사용하여 미래 state(t+1, t+2, ...)의 정보를 차단
▶ 3.2 Attention
▶ 3.2.1 Scaled Dot-Product Attention
Q : query / K : key / V : value d_k : dimension of keys / d_v : dimension of values
dot products of Q with all K : 두 벡터의 유사도 계산
→ divide each by d_k : dot product sacling → apply a softmax function : V에 대한 weight vector 계산 → attention = V와 weight의 가중합
- Dot-product attention은 최적화된 행렬 곱셈으로 구현될 수 있어 빠르고 효율적임 - 하지만 d_k값이 커지면 dot product 값이 너무 커져서 softmax 함수가 매우 작은 gradient를 가지게 만들기 때문에 dot-product attention의 성능이 저하됨
➡️ Dot-product attention에 d_k를 scaling factor로 추가한 attention을 사용
▶ 3.2.2 Multi-Head Attention
Head = parallel attention layers
= 서로 다른 linear projection으로부터 병렬적으로 계산된 Scaled Dot-Product Attention
Q, K, V를 d_k, d_k, d_v 차원으로 linearly projection → Scaled Dot-Product Attention(Head) 계산 → 위 과정을 서로 다른 h개의 linear projection을 사용해 병렬적으로 수행 → h개의 Scaled Dot-Product Attention(Head)를 concat → concat 결과를 한번 더 linear projection하여 multi-head attention 계산
d_model = 512 h = 8 d_k = d_v = d_model / h = 64
- h개의 head를 계산해야하지만 d_model/h로 차원이 d_model의 1/h배로 작아지기 때문에 전체 계산량은 single head attention과 동일
-여러 개의 Scaled Dot-Product Attention 구하고 종합적으로 이용
- 여러 개의 attention mechanism은 서로 다른 representation subspaces를 학습하고 이를 합침으로써 입력 데이터의 정보를 다방면에서 반영할 수 있게 됨 - 서로 다른 특성에 집중하는 representation subspaces의 정보를 종합적으로 사용
➡️ 다양한 representation subspaces의 정보를 동시에 attention할 수 있게 해준다!
▶ 3.2.3 Applications of Attention in our Model
Transformer에선 multi-head attention을 3가지 방법으로 사용
encoder-decoder attention layer : - Decoder Block에 위치한 Multi-Head-Attention - Q는 이전 decoder layer에서 오며, K와 V는 encoder의 output에서 받음 - decoder가 input sequence의 모든 위치에 대해 attend
Self-attention layer in encoder : - Encoder Block에 위치한 Multi-Head-Attention - Q, K, V는 모두 encoder에서 이전 layer의 output으로부터 옴 - encoder의 이전 layer의 모든 위치에 대해 attend
Self-attention layer in decode : - Decoder Block에 위치한 Masked Multi-Head-Attention - Q, K, V는 모두 decoder에서 이전 layer의 output으로부터 옴 - 다만 decoder의 경우 미래 state의 정보를 차단하기 위해 mask를 사용 미래 state에 대해선 attend 하지 않음
▶ 3.3 Position-wise Feed-Forward Networks
input, output 차원 = d_model = 512
은닉층 차원 = 2048
- attention layer 뒤에 위치하는 position-wise fully connected feed-forward network encoder와 decoder의 각 위치마다 서로 다른 parameter를 사용 - 2번의 linear transform + 1번의 ReLU activation function
▶ 3.4 Embeddings and Softmax
two embedding layers : - input과 ouput token을 d_model 차원의 vector로 변환해주는 embedding layer - encoder와 decoder에 input 되기 전 단계에 위치
pre-softmax linear transformation : - decoder output을 predicted next-token probabilities으로 변환해주는 layer - linear transformation + softmax function 구조
위 두 layer는 같은 weight matrix를 사용함
▶ 3.5 Positional Encoding
Positional Encoding = embedding vector에 sequence에서 토큰의 위치에 대한 정보를 주입
- Transformer는 reccurence와 convolution을 사용하지 않기 때문에 sequence 내 토큰들의 위치 정보를 반영해주는 과정이 필요 - embedding vector가 encoder와 decoder에서 입력되기 전에 사용
- Sinusoidal Positional Encoding : sine과 cosine을 이용한 Positional Encoding
pos : 해당 토큰의 position
i : 해당 Positional Encoding vector의 dimension
i가 이 짝수이면 sine 공식, i가 홀수이면 cosine 공식 사용
* 부가 설명출처 : https://gbdai.tistory.com/46
- sequence 길이 * d_momel 크기의 embedding vector - 각 토큰을 PE(position, i)로 표현 가능 - Positional Encoding 식을 이용해 PE값 계산
▶ 4. Why Self-Attention
- 3가지 측면 비교
total computational complexity per layer
amount of computation that can be parallelized (minimum number of sequential operations)
path length between long-range dependencies
n : sequence length
d : representation dimension
k : kernel size of convolutions
r : the size of the neighborhood in restricted self-attention
total computational complexity per layer : - self-attention layer는 n이 d보다 작은 경우 recurrent layer보다 계산 복잡도가 적음 - n이 긴 경우 계산 성능을 향상시키기 위해 sequence에서 r 크기의 이웃만 고려하는 restricted 방법을 사용할 수 있음
amount of computation that can be parallelized (minimum number of sequential operations) : - recurrent layer는 O(n)의, self-attention layer는 O(1)의 sequential operation을 필요 - self-attention layer가 더 많은 병렬 처리가 가능하며 학습 시간을 현저히 줄일 수 있음
path length between long-range dependencies : - self-attention layer가 가장 작은 Maximum path length을 가짐 - self-attention가 Long-range dependencies를 가장 잘 학습 가능함
➡️self-attention는 RNN 기반에서 하기 어려웠던 많은 양의 병렬 처리가 가능하기 때문에 학습 시간을 현저히 줄일 수 있으며, RNN이 가지고 있는 Long term dependency 문제도 개선할 수 있다. 또한 모델로부터 attention distribution을 시각화할 수 있다는 점에서 설명 가능한 모델이라는 장점이 있다.
▶ 5. Training
- standard WMT 2014 English-German dataset, WMT 2014 English-French dataset으로 학습
- 각 훈련 배치에는 약 25000개의 source 토큰와 target 토큰을 포함하는 문장쌍이 포함
- Adam optimizer ( β1=0.9, β2=0.98, ϵ=10^(−9))
- learning rate
- Regularization
Residual-Dropout, P_drop = 0.1 - 각 sub-layer의 output이 다음 sub-layer의 input과 더해지고 정규화되기 전에 dropout - encoder와 decoder에 들어가기 전embeddings와 positional encodings의 합에도 dropout
label smoothing, ϵ_ls=0.1
* dropout : 신경망 학습 과정에서 과적합을 방지하기 위해 사용되는 정규화 기법 임의로 일부 뉴런의 출력을 0으로 만들어
* label smoothing : Hard label(One-hot encoded vector)을 Soft label(라벨이 0과 1 사이의 확률값)로 스무딩 모델의 출력 label이 확률분포로 나오도록 부드럽게 만드는 기법 모델의 일반화 성능을 높여주는 경향이 있음 drop out 다음으로 regularization에서 많이 사용되는 기법 중 하나
- 영어 → 프랑스어 번역에서도 41.0 BLEU socre로 이전 모델들보다 성능이 뛰어남
- Training cost의 경우도 이전 모델들을 ensemble한 모델보다 월등히 작음
➡️ Transformer가 기존의 sota보다 훨씬 적은 훈련 비용과 높은 BLEU 점수를 달성
Transofrmer는 이전 모델보다 성능이 높고 Training cost는 적은 새로운 sota 모델
▶ 6.2 Model Variations
- (A) : Head 개수, d_k, d_v가 달라져도 전체 계산량은 일정 single-head attention(h=1)보다 multi-head attention의 성능이 더 좋음 - (B) : d_k를 줄이는 것이 모델 성능을 저하시킴 - (C), (D) : 큰 모델일수록 성능이 좋고, dropout이 과적합을 피하는데 유용함 - (E) : sinusoidal positional encoding을 learned positional embeddings 바꾸어도 성능은 비슷함
▶ 7. Conclusion
- encoder-decoder 아키텍처에서 가장 일반적으로 사용되는 recurrent layers를 multi-headed self-attention으로 대체함으로써 전적으로 attention mechanism에 기반한 최초의 시퀀스 변환 모델인 Transformer를 제시
- Transformer는 recurrent나 convolutional layer를 기반으로 하는 이전 모델보다 훨씬 빠르게 학습