[논문 리뷰]/자연어처리

[논문 리뷰] Transformer: Attention Is All You Need

johyeongseob 2025. 6. 20. 13:52

논문: https://arxiv.org/abs/1706.03762

저자: Ashish Vaswani* (Google Brain), Noam Shazeer∗ (Google Brain), Niki Parmar∗(Google Research), Jakob Uszkoreit∗ (Google Research), Llion Jones∗ (Google Research), Aidan N. Gomez∗$^†$ (University of Toronto), Łukasz Kaiser∗ (Google Brain), Illia Polosukhin∗$^‡$
∗ Equal contribution, $^†$ Work performed while at Google Brain. $^‡$ Work performed while at Google Research.

인용: Vaswani, Ashish, et al. "Attention is all you need." Advances in neural information processing systems 30 (2017).

코드: https://github.com/tensorflow/tensor2tensor

튜토리얼: https://johyeongseob.tistory.com/53

 

0. 초록

 기존의 문장 번역 모델들은 encoder와 decoder를 가진 RNN 혹은 CNN구조가 바탕이다. 최신 모델도 attention을 추가한 encoder-decoder 구조이다. 저자들은 새로운 모델구조 Transformer를 소개한다. Transformer는 RNN, CNN 없이 attention모듈로만 구성되어 있다.

1. 서론

 최근까지 RNN, LSTM, GRU 모델들은 언어 모델, 기계 번역 등에 사용되어 왔다. 이들은 입력 문장과 이에 따른 출력 문장의 각 단어 위치를 계산하는 방식을 택한다. 이런 특성은 훈련 시, 병렬화를 어렵게 만들고 문장 길이가 길어질수록 계산이 어렵다. Attention machanism이 도입되었지만, 여전히 RNN 모델을 기반으로 한 한계가 있다. 이에 저자들은 위 한계들을 극복하기 위해 Transformer를 제안한다.

2. 관련 연구

 기존 방법들 중 문장 길이에 따른 계산 비용을 낮추려는 시도들이 있었으나, 여전히 문장 길이가 길어질수록 계산 비용은 늘어났다. 이에 Transformer는 Multi-Head Attention을 도입하여 문장 길이에 상관없이 계산 비용이 고정된다. Self-attention은 문장 내 단어들의 위치에 집중하는 구조이다. End-to-end memory networks는 문장 정렬 기반 RNN이 아닌, 문장 내 attention 구조에 적합하다. Transformer는 처음으로 RNN, CNN 을 사용하지 않고 오로지 self-attention 기반으로만 설계된 기계번역 모델이다.

3. 모델 구조

 Transformer는 위 그림과 같이 self-attention과 point-wise, fully connected layer로 구성된 모듈의 반복(stack)으로 구성되어 있다. 

3.1 Encoder and Decoder Stacks

Encoder: 인코더는 $N=6$개의 동일한 layer의 stack으로 구성되어 있다. 각 layer는 두개의 sub-layer를 가진다. 첫 번째는 multi-head self-attention 구조이며, 두 번째는 ㅔposition-wise fully connected feed-forward network이다. 저자들은 각 sub-layer에 residual connection와 layer normalization을 추가한다. 각 sub-layer의 출력 차원은 $d_{model}=512$ 이다.
Decoder: 디코더도 $N=6$개의 동일한 layer의 stack으로 구성되어 있다. 각 layer의 첫 번째와 세 번째 sub-layer는 encoder의 두 sub-layer와 동일한 형태이며, 두 번째 sub-layer는 encoder stack의 출력값에 대한 multi-head attention 이다. 세 개의 sub-layer에 각각 residual connection와 layer normalization을 추가한다. 저자들은 self-attention sub-layer (첫 번째) 를 수정하여, 현재 단어들이 미래 단어들을 참조(attend)하지 못하게 만든다. 두 가지 적용된 수정사항은 masking과 output embedding을 one position offset 이며, 이들을 통해 모델은 $i$번째 단어를 예측할 때, $i$번째 이전 단어들만을 참고한다.

3.2 Attention

 Attention function은 query, key, value를 출력으로 mapping한다. 출력값은 query와 key를 통해 생성한 weight를 value에 element-wise sum한 값이다.

3.2.1 Scaled Dot-Product Attention
 저자들은 자신의 attention 기법을 "Scaled Dot-Product Attention" (왼쪽 그림) 이라고 부른다. 입력은 query와 key $d_k$, 그리고 value $d_v$이다. 모듈은 query를 모든 keys에 대해 dot product를 수행한 다음, scaling factor $\sqrt{d_k}$로 나누고, softmax 연산을 수행하여, 가중치를 얻는다. 

\begin{align*}
    & \text{Attention}(Q, K, V) = \text{softmax}\left( \frac{QK^T}{\sqrt{d_k}} \right) V
    \tag{1}
\end{align*}

위 수식에서 dot-product에서 $d_k$ 값이 커질수록 softmax 연산의 기울기가 작아져 학습이 어려워지므로, scaling factor $\frac{1}{\sqrt{d_k}}$ 를 도입하였다.

3.2.2 Multi-Head Attention
저자들은 attention function을 한 번만 수행하는 것 대신 여러 번 ($h=8$) 병렬적으로 수행한다. query, key, value는 h번 다른 learned linear projection으로 $d_K$, $d_K$, $d_v$ 차원으로 변한다. 이들은 attention을 통해 $d_v$ 차원의 출력값을 얻는다. h개의 결과값은 채널별 합쳐지고, 다시 한 번 project하여 최종 값을 얻는다. 

\begin{align*}
\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \dots, \text{head}_h) W^O \\
\text{where } \text{head}_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)
\end{align*}

여기서 $W_i^Q, W_i^K \in \mathbb{R}^{d_{\text{model}} \times d_k}, W_i^V \in \mathbb{R}^{d_{\text{model}} \times d_v}, W^O \in \mathbb{R}^{h d_v \times d_{\text{model}}}$이며, $d_k = d_v = \frac{ d_{\text{model}} }{h} = 64$ 이다.

입력 차원을 h로 나누어 계산하기 때문에 h개의 multi-head attention의 계산 비용은 full dimension single-head attention과 유사하다.

3.3 Position-wise Feed-Forward Networks

 attention sub-layer 다음으로는 fully connected feed-forward network가 있다. FFN은 단어 개수와 상관없이 개별적으로, 그리고 동일한 weight로 훈련된다. 

\begin{align*}
    & \text{FFN}(x) = \max(0, xW_1 + b_1)W_2 + b_2
    \tag{2}
\end{align*}

수식의 입출력 차원은 $d_{model}=512$ 이고, 중간 레이어 차원값은 $d_{ff}=2048$ 이다.

3.5 Positional Encoding

 저자들은 Transformer 모델이 RNN, CNN을 사용하지 않으면서 문장 내 단어들의 순서를 기억하기 위해, 위치에 대한 정보 (positional encoding) $d_{model}$ 를 encoder/decoder 초반 입력 임베딩에 element-wise sum 한다. 이 연구에서 positional encoding은 sine and cosine 함수를 사용한다.

\begin{align}
PE_{(pos, 2i)} &= \sin\left( \frac{pos}{10000^{2i / d_{\text{model}}}} \right) \\
PE_{(pos, 2i+1)} &= \cos\left( \frac{pos}{10000^{2i / d_{\text{model}}}} \right)
\end{align}

$pos$는 문장 내 단어의 위치이며, $i$는 차원 인덱스이다.