← Back to Blog

[Paper Review] Attention Is All You Need

paper review > natural language processing

2026-07-069 min read

#paper-review #deep-learning #natural-language-processing #transformer #attention

논문 링크: Attention Is All You Need

논문 정보

항목내용
VenueConference on Neural Information Processing Systems (NeurIPS)
출판 시점2017년
저자Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin
소속Google Brain, Google Research, University of Toronto

핵심 아이디어

Transformer는 sequence transduction 문제에서 recurrent layer와 convolution layer를 제거하고, attention만으로 encoder-decoder model을 구성한 architecture이다.

이 논문의 핵심 주장은 다음과 같다.

문장 안의 token들이 서로 어떤 관계를 갖는지는 recurrent computation 없이 self-attention만으로 직접 모델링할 수 있다.

기존 seq2seq model은 보통 RNN, LSTM, GRU 같은 recurrent network를 encoder와 decoder의 기본 단위로 사용했다. 하지만 recurrent model은 token을 순서대로 처리해야 하므로 sequence length가 길어질수록 병렬화가 어렵다. Transformer는 각 token 위치에서 다른 모든 token 위치를 한 번에 참고하는 self-attention을 사용한다.

즉 긴 문장을 다음처럼 시간축으로 순차 처리하지 않는다.

x1x2xnx_1 \rightarrow x_2 \rightarrow \cdots \rightarrow x_n

대신 모든 token 쌍의 관계를 attention score matrix로 한 번에 계산한다.

ARn×nA \in \mathbb{R}^{n \times n}

이 선택이 이후 BERT, GPT, T5, ViT 같은 거의 모든 modern deep learning architecture의 기본 토대가 되었다.


문제 배경

기계 번역처럼 입력 sequence를 출력 sequence로 바꾸는 문제를 sequence transduction이라 한다. 전통적인 encoder-decoder 구조는 다음 형태를 가진다.

구성 요소역할
Encoder입력 token sequence를 hidden representation으로 변환한다.
Decoderencoder representation과 이전 출력 token을 보고 다음 token을 생성한다.
Attentiondecoder가 입력 sequence의 어떤 위치를 참고할지 결정한다.

Transformer 이전에도 attention은 이미 사용되고 있었다. 다만 당시 attention은 대개 RNN encoder-decoder 위에 붙는 보조 장치였다. 논문의 질문은 더 과감하다.

RNN을 중심에 두고 attention을 붙일 것이 아니라, attention 자체를 model의 중심에 두면 안 되는가?

이 질문에 대한 답이 Transformer이다.


전체 Architecture

Transformer는 encoder stack과 decoder stack으로 구성된다. 논문 기본 설정에서는 encoder와 decoder가 각각 N=6N=6개의 layer를 가진다.

Stack한 layer의 주요 sub-layer
EncoderMulti-head self-attention, position-wise feed-forward network
DecoderMasked multi-head self-attention, encoder-decoder attention, position-wise feed-forward network

각 sub-layer 주변에는 residual connection과 layer normalization이 적용된다. 논문은 이를 다음처럼 표현한다.

LayerNorm(x+Sublayer(x))\operatorname{LayerNorm}(x + \operatorname{Sublayer}(x))

이 구조는 두 가지를 동시에 만족시킨다.

  1. Attention으로 token 간 dependency를 직접 계산한다.
  2. Feed-forward network로 각 token 위치의 representation을 비선형적으로 변환한다.

Encoder는 입력 문장의 contextual representation을 만들고, decoder는 이전에 생성한 token들과 encoder 출력을 함께 보면서 다음 token을 autoregressive하게 예측한다.


Scaled Dot-Product Attention

Transformer의 기본 attention은 scaled dot-product attention이다. 입력 representation에서 Query, Key, Value를 만든다.

Q=XWQ,K=XWK,V=XWVQ = XW^Q,\qquad K = XW^K,\qquad V = XW^V

Attention은 Query와 Key의 유사도를 구한 뒤, 그 score로 Value를 weighted sum한다.

Attention(Q,K,V)=softmax(QKdk)V\operatorname{Attention}(Q,K,V) = \operatorname{softmax} \left( \frac{QK^\top}{\sqrt{d_k}} \right)V

각 항의 의미는 다음과 같다.

의미
QQ현재 위치가 무엇을 찾고 있는지 나타낸다.
KK각 위치가 어떤 정보를 제공할 수 있는지 나타낸다.
VV실제로 모아서 전달할 정보이다.
QKQK^\top모든 query-key 쌍의 compatibility score이다.
dk\sqrt{d_k}dot product scale을 안정화하기 위한 normalization이다.

dk\sqrt{d_k}로 나눌까? 차원 dkd_k가 커지면 dot product 값의 분산이 커지고, softmax가 너무 sharp해져 gradient가 작아질 수 있다. 따라서 score를 scale down해서 학습을 안정화한다.


Self-Attention

Self-attention은 Query, Key, Value가 모두 같은 sequence에서 나온다는 뜻이다. Encoder self-attention에서는 입력 sequence의 모든 위치가 서로를 볼 수 있다.

Q,K,V=XWQ,XWK,XWVQ,K,V = XW^Q, XW^K, XW^V

이때 attention score matrix는 다음 모양이다.

QKRn×nQK^\top \in \mathbb{R}^{n \times n}

ii번째 token이 jj번째 token을 얼마나 참고할지 모든 token 쌍에 대해 계산한다. RNN에서는 멀리 떨어진 token 사이의 정보가 여러 time step을 거쳐 이동해야 한다. 반면 self-attention에서는 두 token 사이의 path length가 상수에 가깝다.

Layer typeSequential operationsMaximum path length
Self-attentionO(1)O(1)O(1)O(1)
RecurrentO(n)O(n)O(n)O(n)
ConvolutionalO(1)O(1)O(logkn)O(\log_k n)

이것이 Transformer가 긴 dependency를 학습하기 좋은 이유 중 하나다. 다만 self-attention은 full attention matrix를 만들기 때문에 sequence length에 대해 O(n2)O(n^2) 비용을 가진다. 이 한계는 이후 Linformer, Performer, Longformer 같은 efficient Transformer 연구의 출발점이 되었다.


Multi-Head Attention

하나의 attention head만 사용하면 모든 관계를 하나의 attention distribution으로 평균내야 한다. Transformer는 여러 head를 병렬로 두어 서로 다른 representation subspace와 위치 관계를 보게 한다.

MultiHead(Q,K,V)=Concat(head1,,headh)WO\operatorname{MultiHead}(Q,K,V) = \operatorname{Concat}(\operatorname{head}_1,\dots,\operatorname{head}_h)W^O

각 head는 다음과 같다.

headi=Attention(QWiQ,KWiK,VWiV)\operatorname{head}_i = \operatorname{Attention} \left( QW_i^Q, KW_i^K, VW_i^V \right)

논문 기본 모델은 h=8h=8개의 head를 사용한다. dmodel=512d_{\text{model}}=512이고 각 head의 key/value dimension은 다음과 같다.

dk=dv=dmodelh=64d_k = d_v = \frac{d_{\text{model}}}{h} = 64

따라서 head를 8개로 나누어도 전체 계산량은 full dimension single-head attention과 비슷하게 유지된다. 대신 각 head가 서로 다른 관계를 학습할 수 있다.

Transformer에서는 multi-head attention이 세 곳에서 쓰인다.

위치QueryKey/Value의미
Encoder self-attentionencoder stateencoder state입력 token끼리 서로 참고한다.
Decoder masked self-attentiondecoder statedecoder state이전 출력 token만 참고한다.
Encoder-decoder attentiondecoder stateencoder output출력 token이 입력 문장의 관련 위치를 참고한다.

Masked Self-Attention

Decoder는 autoregressive model이다. 즉 yiy_i를 예측할 때 미래 token yi+1,yi+2,y_{i+1}, y_{i+2}, \dots를 보면 안 된다.

그래서 decoder self-attention에서는 미래 위치를 mask한다. Attention score matrix에서 볼 수 없는 위치를 -\infty로 바꾸면 softmax 이후 probability가 0이 된다.

예를 들어 4개 token이 있을 때 decoder attention mask는 다음처럼 이해할 수 있다.

Query position볼 수 있는 Key position
11
21, 2
31, 2, 3
41, 2, 3, 4

이 mask 덕분에 decoder는 병렬로 학습되면서도 generation rule은 causal하게 유지한다.


Position-Wise Feed-Forward Network

Attention sub-layer 뒤에는 각 position에 독립적으로 적용되는 feed-forward network가 있다.

FFN(x)=max(0,xW1+b1)W2+b2\operatorname{FFN}(x) = \max(0, xW_1 + b_1)W_2 + b_2

이 network는 모든 position에 같은 parameter를 공유해서 적용된다. 다르게 말하면 kernel size가 1인 convolution 두 개를 적용하는 것과 비슷하다.

논문 기본 설정은 다음과 같다.

Hyperparameter
dmodeld_{\text{model}}512
dffd_{\text{ff}}2048
ActivationReLU

Attention이 token 간 정보를 섞는 역할이라면, feed-forward network는 각 token representation을 더 풍부하게 변환하는 역할이다.


Positional Encoding

Transformer는 recurrence와 convolution을 사용하지 않는다. 따라서 architecture 자체에는 token 순서 정보가 없다. 이를 보완하기 위해 input embedding에 positional encoding을 더한다.

zt=Embedding(xt)+PE(t)z_t = \operatorname{Embedding}(x_t) + \operatorname{PE}(t)

논문은 sine과 cosine을 이용한 fixed positional encoding을 사용한다.

PE(pos,2i)=sin(pos100002i/dmodel)\operatorname{PE}_{(pos,2i)} = \sin \left( \frac{pos}{10000^{2i/d_{\text{model}}}} \right) PE(pos,2i+1)=cos(pos100002i/dmodel)\operatorname{PE}_{(pos,2i+1)} = \cos \left( \frac{pos}{10000^{2i/d_{\text{model}}}} \right)

이 방식의 의도는 상대 위치 정보를 선형적으로 다루기 쉽게 만드는 것이다. 논문에서는 learned positional embedding도 실험했지만, 성능은 거의 비슷했다고 보고한다. 저자들은 더 긴 sequence length로 extrapolation할 가능성을 고려해 sinusoidal encoding을 선택했다.


왜 Self-Attention인가

논문이 self-attention을 선택한 이유는 크게 세 가지다.

기준설명
계산 복잡도layer당 계산량이 실용적인 범위에 있다.
병렬화token을 순차 처리하지 않아 학습 병렬화가 쉽다.
장거리 의존성먼 token 사이의 path length가 짧다.

RNN은 hidden state를 순서대로 업데이트해야 한다. 따라서 한 training example 안에서 time dimension 병렬화가 제한된다. 반면 Transformer는 attention matrix를 한 번에 만들 수 있으므로 GPU matrix multiplication을 적극적으로 활용할 수 있다.

또한 long-range dependency 관점에서도 self-attention은 유리하다. 두 token이 문장 안에서 멀리 떨어져 있어도 attention 한 번으로 직접 연결될 수 있다.

단점도 있다. Full self-attention은 sequence length nn에 대해 attention matrix가 n×nn \times n이므로, 시간과 메모리 비용이 O(n2)O(n^2)로 증가한다. 짧거나 중간 길이의 문장 번역에서는 큰 장점이지만, 매우 긴 문서나 고해상도 이미지에서는 병목이 된다.


학습 설정

논문은 WMT 2014 English-German과 English-French 기계 번역 task에서 Transformer를 평가한다.

항목설정
English-German data약 450만 문장 쌍
English-French data약 3600만 문장 쌍
Hardware8 NVIDIA P100 GPUs
Base model training100,000 steps, 약 12시간
Big model training300,000 steps, 약 3.5일
OptimizerAdam
Adam betasβ1=0.9\beta_1=0.9, β2=0.98\beta_2=0.98
Warmup steps4000
Label smoothingϵls=0.1\epsilon_{ls}=0.1

Learning rate schedule도 이 논문의 중요한 구현 요소다.

lrate=dmodel0.5min(step0.5,stepwarmup1.5)\operatorname{lrate} = d_{\text{model}}^{-0.5} \cdot \min \left( \operatorname{step}^{-0.5}, \operatorname{step}\cdot \operatorname{warmup}^{-1.5} \right)

초기에는 learning rate를 선형적으로 키우고, warmup 이후에는 step 수의 inverse square root에 비례해 줄인다. 현재 Transformer 계열 모델에서 warmup schedule이 자주 쓰이는 배경도 이 논문과 연결된다.


실험 결과

기계 번역 결과에서 Transformer는 당시 strong baseline보다 높은 BLEU를 달성했다.

ModelWMT14 EN-DE BLEUWMT14 EN-FR BLEU
Transformer base27.338.1
Transformer big28.441.8

특히 English-German에서는 기존 ensemble model보다도 2 BLEU 이상 높은 성능을 보였고, training cost도 더 낮았다. English-French에서도 single model 기준으로 강한 성능을 보였다.

논문은 constituency parsing에도 Transformer를 적용한다. Task-specific architecture를 많이 바꾸지 않았는데도 WSJ parsing에서 경쟁력 있는 F1 score를 얻었다. 이는 Transformer가 단순히 번역 전용 architecture가 아니라, sequence modeling 일반에 쓸 수 있는 구조라는 점을 보여준다.


이 논문의 기여

Transformer의 기여는 단순히 attention을 잘 쓴 모델을 제안했다는 정도가 아니다. Architecture의 기본 가정을 바꾸었다.

기여의미
Recurrence 제거sequence modeling에서 RNN이 필수라는 가정을 깼다.
Self-attention 중심 구조token 간 dependency를 직접적인 pairwise interaction으로 모델링했다.
Multi-head attention여러 관계를 서로 다른 subspace에서 병렬로 학습하게 했다.
Positional encoding순서 정보가 없는 attention 구조에 위치 정보를 주입했다.
병렬 학습긴 sequence를 순차 처리하지 않아 GPU 활용성이 좋아졌다.

가장 중요한 변화는 hidden state를 시간 순서대로 전달하는 관점에서 벗어난 것이다. Transformer는 sequence를 graph처럼 본다. 각 token은 attention edge를 통해 다른 token과 직접 연결된다.


한계

Transformer는 매우 강력하지만, 원 논문 구조에도 한계가 있다.

  1. Self-attention 비용이 O(n2)O(n^2)이다. Sequence length가 길어질수록 attention matrix가 빠르게 커진다.

  2. 위치 정보가 architecture에 내장되어 있지 않다. Positional encoding을 더해야 순서 정보를 사용할 수 있다.

  3. Decoder generation은 여전히 autoregressive하다. 학습은 병렬화하기 쉽지만 inference에서는 token을 하나씩 생성해야 한다.

  4. Attention이 항상 해석 가능한 근거는 아니다. Attention weight가 높다고 해서 반드시 모델의 causal explanation이라고 보기는 어렵다.

  5. Long context에서는 global attention이 비싸다. 이후 연구들은 sparse attention, linear attention, sliding window attention 등으로 이 문제를 줄이려 했다.


정리

이 논문의 메시지는 제목 그대로다.

Sequence modeling에서 핵심은 recurrence가 아니라 attention일 수 있다.

Transformer는 입력 token 사이의 관계를 직접 계산하고, decoder는 masking을 통해 autoregressive generation을 유지한다. 전체 구조는 다음 식 하나로 압축해서 볼 수 있다.

Attention(Q,K,V)=softmax(QKdk)V\boxed{ \operatorname{Attention}(Q,K,V) = \operatorname{softmax} \left( \frac{QK^\top}{\sqrt{d_k}} \right)V }

이 수식은 단순하지만 영향은 컸다. RNN 기반 seq2seq model의 병렬화 한계를 넘었고, 이후 NLP와 vision, speech, multimodal model의 기본 building block이 되었다.

오늘날의 LLM은 원 논문과 비교하면 훨씬 크고, normalization 위치나 activation, positional encoding, attention implementation도 많이 달라졌다. 그럼에도 핵심은 여전히 같다.

Token이 다른 token을 직접 바라보고, 그 관계를 학습 가능한 representation으로 바꾸는 것이다.