본문 바로가기
목차
ML

Multi-Head "Masked/Cross" Attention - Transformer Decoder

by ds31x 2026. 4. 18.
728x90
반응형

이 문서는

  • Transformer의 Encoder에서의
    • Multi-Head Self-Attention과
    • Position-wise Feed Forward Network에 대한 아래 글에 이어서
  •  Decoder의
    • Masked Multi-Head Self-Attention과
    • Multi-Head Cross-Attention에 대해 설명하는 글임.

2026.04.07 - [ML] - Multi-Head Self Attention - Transformer Encoder

 

Multi-Head Self Attention - Transformer Encoder

Multi-Head Self-Attention입력 sequence의 각 token이 같은 sequence 내부의 다른 모든 token을 참고하여,문맥적으로 중요한 정보에 더 크게 반응하도록 만드는 Transformer의 핵심 mechanism임.위의 내용은 (Single-Head

ds31x.tistory.com

 

앞서 Encoder에서의 Multi-Head Self-Attention은

  • 입력 sequence 내부의 각 token이 같은 sequence 안의 다른 token들을 참고하여,
  • 문맥이 반영된 표현을 만드는 과정으로 볼 수 있었음.

Decoder에서도 attention이 핵심 역할을 담당하지만, Encoder와는 조금 구조가 다름.

 

그 이유는

  • Decoder가 출력 sequence를 한 token씩 생성하는 autoregressive generation 구조를 가지며,
  • 동시에 Encoder가 만든 (context를 반영한) 출력 표현(=representation)들도 함께 참고해야 하기 때문임.

0. Decoder Block의 전체 구조

Encoder layer는 보통 다음의 두 sub-layer로 구성됨.

  1. Multi-Head Self-Attention(다중 헤드 자기-어텐션)
  2. Position-wise Feed-Forward Network(위치별 피드포워드 네트워크)

 

반면 Decoder layer는 다음의 세 sub-layer로 구성됨.

  1. Masked Multi-Head Self-Attention(마스킹된 다중 헤드 자기-어텐션: 아래 빨간 박스)
  2. Multi-Head Cross-Attention(인코더-디코더 어텐션: 위의 빨간 박스)
  3. Position-wise Feed-Forward Network

 

즉, Decoder에서는 attention이 두 번 사용됨.

  • 첫 번째 attention은 Decoder 내부 token들 사이의 관계를 다루는 self-attention
  • 두 번째 attention은 Encoder의 출력 표현들을 참고하는 encoder-decoder attention

1. Masked Multi-Head Self-Attention

Decoder의 첫 번째 attention은 self-attention임.

즉, Query, Key, Value가 모두 Decoder 쪽 입력으로부터 만들어짐.

 

동작 자체는 Encoder의 multi-head self-attention과 거의 같음.

  • 각 head가 Scaled Dot-Product Attention을 독립적으로 수행하고
  • 각 head의 출력을 concat한 뒤 다시 projection을 적용함

다만 Decoder에서는 여기에 중요한 제약이 추가됨.

 

바로 Decoder에선
미래 token을 보지 못하도록
(causal) mask를 적용한다는 점임.

 

즉, Decoder의 self-attention에는 causal mask(인과 마스크) 또는 look-ahead mask(미래 참조 차단 마스크)가 적용됨.


1-1. Causal Mask의 필요성

예를 들어 출력 문장이 다음과 같다고 하자.

  • <CLS>
  • 나는
  • 밥을
  • 먹는다
  • <SEP>

Decoder가 밥을 위치의 token을 예측하는 시점이라면, 이 위치의 Query는 현재 위치 이후의 token을 참고해서는 안 됨.

아직 생성되지 않은 미래 token까지 참고하면, autoregressive generation의 조건이 깨지기 때문임.

 

따라서 Decoder의 self-attention에서는 현재 위치보다 뒤쪽에 있는 token들에 대한 attention score를 차단함.

 

즉, Decoder의 self-attention이 subsequent positions를 보지 못하도록 masking 됨.


1-2. Causal Mask의 동작 방식

Scaled Dot-Product Attention의 계산은 다음과 같음.

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

* 여기서 causal mask는 $QK^\top$로부터 얻어진 attention score matrix에 적용됨.

* 일반적으로는 padding mask와 causal mask를 함께 반영하여, 참조하면 안 되는 위치의 score가 softmax 이후 0이 되도록 처리함: score가 -inf인 경우 softmax에서 0이 됨.

 

이는

* 미래 위치에 해당하는 token의 attention score를 매우 작은 값으로 만들어,

* 그 위치의 Value가 현재 Query에 반영되지 않도록 하는 것임.

 

개념적으로 길이가 4인 sequence에 대한 causal mask는 다음과 같은 하삼각 행렬(lower triangular matrix)형태로 볼 수 있음.

$$
\begin{bmatrix}
1 & 0 & 0 & 0 \\
1 & 1 & 0 & 0 \\
1 & 1 & 1 & 0 \\
1 & 1 & 1 & 1
\end{bmatrix}
$$

  • 이는 각 위치가 자신과 그 이전 위치들만 볼 수 있음을 의미함.

1-3. Encoder의 Self-Attention과의 차이

Encoder의 self-attention은 입력 sequence 전체를 자유롭게 참조할 수 있음.

이는 Encoder의 목적이 입력 전체를 문맥적으로 반영한 출력 표현들로 변환하는 데 있기 때문임.

 

반면 Decoder의 self-attention은 미래 token을 참조할 수 없음.

따라서 Decoder에서는 masked self-attention이 필요함.

 

요약해서 정리하면 다음과 같음.

  • Encoder self-attention: 입력 전체 참조 가능
  • Decoder self-attention: 현재 위치 이후 참조 불가
  • 따라서 Decoder에는 causal mask가 적용된 masked self-attention이 사용됨

2. Multi-Head Cross-Attention

Decoder의 두 번째 attention은 Encoder-Decoder Attention이며, 흔히 Cross-Attention이라고도 부름.

 

이 attention에서는

  • Query는 Decoder에서 오고
  • Key와 Value는 Encoder의 출력에서 옴

ref. https://kongsberg.tistory.com/47

 

즉,  Decoder

  • 지금까지 생성한 출력의 표현을 바탕으로,
  • Encoder가 만든 출력 전체 표현들 가운데 어떤 부분이 현재 token 생성에 중요한지를 선택적으로 참고함.

 

논문 표현에 가깝게 말하면,

Decoder는
encoder의 output representations 에
attention을 수행하는 것임.
Cross-Attention

 

Transformer의 task인 "기계번역"의 관점에서 보면 다음과 같이 이해할 수 있음.

  • Encoder는 입력 문장을 출력 표현들의 sequence로 변환하고
  • Decoder는 현재까지 생성한 출력 문맥을 바탕으로
  • 입력 문장의 어느 부분에 대응하는 정보가 필요한지를 encoder-decoder attention으로 찾음

따라서 이 sub-layer는 입력 sequence와 출력 sequence를 연결하는 역할을 담당함.


3. Decoder에 두 종류의 Attention이 필요한 이유

앞서 언급한 대로, Decoder는 다음의  두 가지 정보를 동시에 활용해야 함.

  • 첫째, 지금까지 생성한 자신(Decoder) 출력 token들 사이의 관계를 알아야 함: masked self-attention
  • 둘째, Encoder가 만든 출력 표현들(context vector) 중 현재 출력 token 생성에 필요한 정보를 가져와야 함: cross-attention

즉,

  • masked self-attention출력 sequence 내부의 과거 문맥을 반영하고
  • cross-attention은 입력 sequence에서 유래한 정보를 Encoder의 출력 표현들을 통해 참조

이 두 역할이 분리되어 있기 때문에 Decoder에는 두 종류의 attention이 존재함.


4. Position-wise Feed-Forward Network

Decoder의 Position-wise Feed-Forward Network는 Encoder에서와 동일한 역할을 수행함.

  • attention은 token들 사이의 관계를 반영하여 weighted sum을 계산하는 구조이고,
  • Position-wise Feed-Forward Network는
    • 각 position에 동일한 parameter를 갖는 feed-forward network를 독립적으로 적용하여
    • 비선형 변환을 추가함.

즉,

  • attention은 token 간 관계를 반영하고
  • feed-forward network는 각 position의 표현을 한 번 더 비선형적으로 변환함

요약

Transformer의 관점에서 보면 다음과 같음:

Encoder

  • 입력 sequence 전체를 문맥적으로 해석하여 출력 표현들의 sequence를 생성하는 부분

Decoder

  • 지금까지 생성한 출력과 Encoder의 출력 표현들을 함께 사용하여 다음 token을 예측하는 부분
  • 이때 Decoder의 핵심 제약은 미래 token을 볼 수 없다는 점이며, 이를 구현하는 장치가 Masked Multi-Head Self-Attention임.

 

최종적으로 Decoder layer는 다음과 같이 이해할 수 있음.

  • Masked Multi-Head Self-Attention: 출력 sequence의 과거 정보만 참고
  • Encoder-Decoder Attention: Encoder의 출력 표현들을 참고
  • Position-wise Feed-Forward Network: 각 position의 표현을 비선형적으로 변환

또한,

  • padding mask는 서로 다른 길이의 sequence를 처리하기 위해 사용되고
  • causal mask는 autoregressive generation을 위해 미래 token 참조를 차단하며
  • multi-head 구조는 서로 다른 관계를 여러 head에서 병렬적으로 학습할 수 있게 함

같이보면 좋은 자료들

https://ds31x.github.io/wiki/review/2017_Attention_is_all_you_need/

 

Transformer

Attention is all you need

ds31x.github.io

 

https://arxiv.org/pdf/1706.03762

 

728x90