Transformer
Transformer Architecture
셀프 어텐션 기반 신경망 구조. GPT, BERT, Claude의 기반. 2017년 "Attention Is All You Need"로 제안.
Transformer Architecture
셀프 어텐션 기반 신경망 구조. GPT, BERT, Claude의 기반. 2017년 "Attention Is All You Need"로 제안.
Transformer는 2017년 Google의 "Attention Is All You Need" 논문에서 제안된 딥러닝 아키텍처로, 현대 AI의 근간을 이루는 핵심 구조입니다. RNN이나 CNN 없이 오직 어텐션 메커니즘만으로 시퀀스를 처리하여 병렬 연산이 가능하고, 장거리 의존성을 효과적으로 포착합니다.
핵심 구성 요소는 Self-Attention(입력 시퀀스 내 모든 위치 간 관계 학습), Multi-Head Attention(다양한 관점의 어텐션 동시 수행), Positional Encoding(순서 정보 주입), Feed-Forward Network(비선형 변환)입니다. 인코더-디코더 구조가 원형이지만, BERT(인코더만), GPT(디코더만) 등 변형이 널리 사용됩니다.
Transformer의 등장으로 NLP는 물론 컴퓨터 비전(ViT), 음성(Whisper), 멀티모달(CLIP) 등 모든 분야에서 패러다임 전환이 일어났습니다. GPT-4, Claude, Gemini 등 최신 LLM은 모두 Transformer 기반이며, 스케일링 법칙에 따라 모델 크기와 데이터를 늘릴수록 성능이 향상되는 특성이 있습니다.
실무에서 Transformer를 직접 구현하는 경우는 드물지만, 구조를 이해하면 모델 선택, 하이퍼파라미터 튜닝, 성능 최적화에 큰 도움이 됩니다. 특히 어텐션 복잡도(O(n²))로 인한 긴 시퀀스 처리 한계와 이를 극복하기 위한 기법들(Flash Attention, Sparse Attention 등)을 알아두면 좋습니다.
# Transformer 핵심 구조 이해를 위한 간단한 Self-Attention 구현
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class SelfAttention(nn.Module):
"""Scaled Dot-Product Self-Attention"""
def __init__(self, d_model, n_heads):
super().__init__()
self.d_model = d_model
self.n_heads = n_heads
self.d_k = d_model // n_heads
# Query, Key, Value 선형 변환
self.W_q = nn.Linear(d_model, d_model)
self.W_k = nn.Linear(d_model, d_model)
self.W_v = nn.Linear(d_model, d_model)
self.W_o = nn.Linear(d_model, d_model)
def forward(self, x, mask=None):
batch_size, seq_len, _ = x.shape
# Q, K, V 계산 및 헤드 분리
Q = self.W_q(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
K = self.W_k(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
V = self.W_v(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
# Scaled Dot-Product Attention
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, float('-inf'))
attn_weights = F.softmax(scores, dim=-1)
context = torch.matmul(attn_weights, V)
# 헤드 결합 및 출력 변환
context = context.transpose(1, 2).contiguous().view(batch_size, seq_len, self.d_model)
return self.W_o(context)
# 사용 예시
d_model, n_heads, seq_len, batch_size = 512, 8, 100, 32
attention = SelfAttention(d_model, n_heads)
x = torch.randn(batch_size, seq_len, d_model)
output = attention(x) # [32, 100, 512]
print(f"Input: {x.shape} → Output: {output.shape}")
"Transformer 기반 모델을 쓸 건데, 입력이 10K 토큰까지 갈 수 있어요. 기본 어텐션은 O(n²)이라 메모리가 터지니까 Flash Attention이나 Longformer 같은 효율적인 구현을 고려해야 합니다. A100 80GB 기준으로 얼마나 배치 사이즈를 가져갈 수 있는지 프로파일링부터 해봐야 할 것 같아요."
"Transformer가 RNN을 대체한 핵심 이유는 병렬화입니다. RNN은 순차적으로 처리해야 하지만, Transformer의 Self-Attention은 모든 위치를 동시에 계산할 수 있어요. 또한 장거리 의존성을 한 번의 어텐션으로 직접 연결해서 gradient vanishing 문제도 완화됩니다."
"GPT는 Transformer의 디코더만 사용하고, BERT는 인코더만 사용합니다. 생성 태스크에는 디코더 기반이, 이해 태스크에는 인코더 기반이 유리해요. 우리 태스크는 분류니까 BERT 계열로 가고, 나중에 요약 기능 추가하면 T5처럼 인코더-디코더 구조를 검토하죠."
| 구조 | 대표 모델 | 특징 | 적합 태스크 |
|---|---|---|---|
| 인코더 전용 | BERT, RoBERTa | 양방향 문맥 | 분류, NER, QA |
| 디코더 전용 | GPT, Claude, Llama | 자기회귀 생성 | 텍스트 생성, 대화 |
| 인코더-디코더 | T5, BART | seq2seq | 번역, 요약 |
💡 실무 팁: 최신 LLM은 대부분 디코더 전용 구조. GPT-4, Claude, Gemini 모두 이 계열입니다. 이해 태스크도 프롬프팅으로 해결 가능하여 실무에서는 디코더 기반이 범용적으로 사용됩니다.
표준 Self-Attention은 시퀀스 길이의 제곱에 비례하는 메모리를 사용합니다. 긴 문서 처리 시 Flash Attention, Sparse Attention 등 효율적인 구현을 사용하거나 Longformer, BigBird 같은 선형 복잡도 모델을 고려하세요.
학습된 위치 임베딩은 학습 시 본 길이를 넘어서면 성능이 급격히 저하됩니다. RoPE, ALiBi 같은 상대적 위치 인코딩으로 개선할 수 있지만, 여전히 길이 일반화는 Transformer의 주요 연구 과제입니다.
추론 시 KV 캐시가 배치 크기와 시퀀스 길이에 비례하여 증가합니다. 대규모 서빙에서는 Grouped Query Attention(GQA)이나 Multi-Query Attention(MQA)으로 캐시 크기를 줄이는 것이 필수적입니다.