Deep Learning study
어텐션 메커니즘: Seq2Seq부터 Transformer까지 본문
어텐션 메커니즘: Seq2Seq부터 Transformer까지
포스트 요약: RNN 기반 Seq2Seq 모델의 성능 한계를 극복한 어텐션(attention) 개념을 시작으로, Scaled Dot-Product Attention, Multi-Head Attention의 수식 유도와 PyTorch 구현 예시까지 심층 분석합니다.
1. 어텐션의 필요성
기존의 Seq2Seq 모델은 고정된 길이의 context 벡터만으로 전체 입력 시퀀스를 요약하기 때문에 긴 문장을 처리할 때 정보 손실이 발생합니다. 어텐션은 디코더가 매 타임스텝마다 인코더의 모든 히든 스테이트에 가중합을 적용해, 입력의 중요한 부분을 동적으로 참조할 수 있게 합니다.[1]
1.1 직관적 예시
“나는 사과를 먹었다”를 영어로 번역할 때, “eat”을 생성할 때는 “먹었다”보다 “사과”에 더 주목해야 합니다. 어텐션은 이런 단어 간 중요도(어텐션 가중치)를 자동으로 학습합니다.
2. Scaled Dot-Product Attention
2.1 수식 정의
쿼리(query), 키(key), 값(value) 벡터 \(\mathbf{Q}, \mathbf{K}, \mathbf{V}\)에 대해,
\[ \mathrm{Attention}(\mathbf{Q},\mathbf{K},\mathbf{V}) = \mathrm{softmax}\!\biggl(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\biggr)\mathbf{V} \]
- \(d_k\): 키 벡터 차원 (스케일링 방지)
- 소프트맥스로 각 쿼리에 대한 키의 유사도를 정규화
2.2 구현 예시 (PyTorch)
import torch
import torch.nn.functional as F
def scaled_dot_product_attention(Q, K, V, mask=None):
dk = Q.size(-1)
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(dk)
if mask is not None:
scores = scores.masked_fill(mask == 0, float('-1e9'))
attn = F.softmax(scores, dim=-1)
return torch.matmul(attn, V), attn
# 예시 입력
Q = torch.randn(2, 4, 64) # (batch, seq_len, d_k)
K = torch.randn(2, 6, 64)
V = torch.randn(2, 6, 64)
output, weights = scaled_dot_product_attention(Q, K, V)
3. Multi-Head Attention
여러 개의 어텐션 헤드를 병렬로 실행해, 다양한 표현 하위공간(subspace)에서 정보를 추출합니다:
\[ \mathrm{MultiHead}(Q,K,V)=\mathrm{Concat}(\mathrm{head}_1,\dots,\mathrm{head}_h)W^O, \quad \mathrm{head}_i=\mathrm{Attention}(QW_i^Q,KW_i^K,VW_i^V) \]
3.1 PyTorch 구현 (torch.nn.MultiheadAttention)
import torch.nn as nn
mha = nn.MultiheadAttention(embed_dim=512, num_heads=8, dropout=0.1)
# 입력: (seq_len, batch, embed_dim)
query = key = value = torch.randn(10, 32, 512)
out, attn_weights = mha(query, key, value)
4. 어텐션 적용 사례
- 기계 번역: Transformer (Vaswani et al., 2017)[2]
- 문장 분류: BERT, RoBERTa 등의 사전학습 모델
- 이미지 자막 생성: CNN+Attention 기반 Encoder–Decoder
4.1 Transformer 구조
from torch import nn
class TransformerBlock(nn.Module):
def __init__(self, embed_dim, num_heads):
super().__init__()
self.mha = nn.MultiheadAttention(embed_dim, num_heads)
self.ffn = nn.Sequential(nn.Linear(embed_dim, 2048), nn.ReLU(), nn.Linear(2048, embed_dim))
self.norm1 = nn.LayerNorm(embed_dim)
self.norm2 = nn.LayerNorm(embed_dim)
def forward(self, x):
attn_out, _ = self.mha(x, x, x)
x = self.norm1(x + attn_out)
ffn_out = self.ffn(x)
return self.norm2(x + ffn_out)
5. 비교 표: Attention 변형
| 기법 | 특징 | 용도 |
|---|---|---|
| Dot-Product | 간단·효율적 | Transformer |
| Additive | 비선형성 포함 | 초기 Seq2Seq |
| Self-Attention | 자기 참조 | 언어모델, BERT |
6. 결론 및 다음 단계
- Scaled vs Additive Attention 비교 실험
- Attention Visualization: 히트맵 도구 활용
- Transformers 심층 분석: Layer 수, Head 수 최적화
참고 문헌
- Bahdanau, D., Cho, K., & Bengio, Y. (2015). Neural Machine Translation by Jointly Learning to Align and Translate. ICLR.
- Vaswani, A., et al. (2017). Attention is All You Need. NeurIPS.
'AI > Pytorch' 카테고리의 다른 글
| 딥러닝 모델 배포: TorchScript vs ONNX 비교 (0) | 2025.04.17 |
|---|---|
| 컨볼루션 신경망(CNN) 동작 원리 한눈에 보기 (0) | 2025.04.17 |
| GPU 메모리·연산 효율 최적화 팁 (0) | 2025.04.17 |
| 자주 만나는 PyTorch 에러 해결법 모음 (0) | 2025.04.17 |
| 데이터 증강(Data Augmentation) 기법 모아보기 (0) | 2025.04.17 |