소개: 트랜스포머 혁명
I 트랜스포머, "Attention Is All You Need"(2017) 논문에 소개된 내용은 다음과 같습니다. AI에 혁명을 일으켰습니다. GPT에서 BERT까지, DALL-E에서 Stable Diffusion까지, Claude에서 Gemini까지: 모두 예 Transformer 아키텍처를 기반으로 합니다. 그들의 성공 비결은 메커니즘에 있다. 자기 관심, 파일 없이 장거리 종속성을 캡처할 수 있습니다. 반복 네트워크의 제한 사항.
무엇을 배울 것인가
- 쿼리, 키, 값: 세 가지 선형 투영
- Scaled Dot-Product Attention: 중심 공식
- 왜 d의 루트로 나누는가?
- Multi-Head Attention: 다양한 관점
- 위치 인코딩: 반복 없이 순서 추가
- NumPy의 단계별 구현
Q, K, V 예측: 데이터에 대한 세 가지 관점
Attention 메커니즘은 입력의 세 가지 선형 변환에 대해 작동합니다. \\mathbf{X} \\in \\mathbb{R}^{n \\times d_{\\text{모델}}}:
어디 \\mathbf{W}^Q, \\mathbf{W}^K \\in \\mathbb{R}^{d_{\\text{모델}} \\times d_k} e \\mathbf{W}^V \\in \\mathbb{R}^{d_{\\text{모델}} \\times d_v}.
직관:
- 쿼리 (\\mathbf{Q}): "내가 뭘 찾고 있는 거지?" - 각 토큰이 묻는 질문
- 열쇠 (\\mathbf{K}): "무엇을 제공하나요?" - 각 토큰의 라벨
- Value (\\mathbf{V}): "내 콘텐츠는 무엇인가요?" - 실제 정보
어텐션 메커니즘은 각 쿼리와 모든 키 간의 유사성을 계산하고 이를 사용합니다. 유사점을 가중치로 적용하고 해당 값을 결합합니다.
스케일링된 내적 주의
Transformers의 중심 공식:
단계별:
- \\mathbf{Q} \\mathbf{K}^T \\in \\mathbb{R}^{n \\times n}: 모든 토큰 간의 유사성 행렬(내적)
- 나누기 기준 \\sqrt{d_k}: 수치적 안정성을 위한 스케일링
- 소프트맥스 행당: 점수를 합이 1이 되는 가중치(확률)로 변환합니다.
- 곱하기 \\mathbf{V}: 값의 가중 평균
왜 스케일링 팩터인가?
없이 \\sqrt{d_k}, 내적은 벡터의 크기에 따라 커집니다. 만약에 q e k 신분증이 있어요 평균 0e의 구성 요소 분산 1이면 다음과 같습니다.
큰 값의 경우 d_k, 스칼라 곱은 매우 값을 갖습니다. 크거나 매우 작아서 소프트맥스를 포화 영역(거의 0에 가까운 기울기)으로 가져옵니다. 나누기 \\sqrt{d_k}, 분산은 1로 돌아갑니다.
import numpy as np
def softmax(x, axis=-1):
exp_x = np.exp(x - np.max(x, axis=axis, keepdims=True))
return exp_x / np.sum(exp_x, axis=axis, keepdims=True)
def scaled_dot_product_attention(Q, K, V, mask=None):
"""Scaled Dot-Product Attention."""
d_k = Q.shape[-1]
# 1. Calcola punteggi di similarità
scores = Q @ K.transpose(0, 2, 1) if Q.ndim == 3 else Q @ K.T
scores = scores / np.sqrt(d_k)
# 2. Applica mask (opzionale, per decoder)
if mask is not None:
scores = np.where(mask == 0, -1e9, scores)
# 3. Softmax per ottenere pesi di attenzione
attention_weights = softmax(scores)
# 4. Media pesata dei Value
if Q.ndim == 3:
output = attention_weights @ V
else:
output = attention_weights @ V
return output, attention_weights
# Esempio: sequenza di 4 token, dimensione 8
np.random.seed(42)
seq_len, d_model, d_k = 4, 8, 8
X = np.random.randn(seq_len, d_model)
# Matrici di proiezione
W_Q = np.random.randn(d_model, d_k) * 0.1
W_K = np.random.randn(d_model, d_k) * 0.1
W_V = np.random.randn(d_model, d_k) * 0.1
# Proiezioni
Q = X @ W_Q
K = X @ W_K
V = X @ W_V
# Attention
output, weights = scaled_dot_product_attention(Q, K, V)
print(f"Input shape: {X.shape}")
print(f"Attention weights:\n{np.round(weights, 3)}")
print(f"Output shape: {output.shape}")
Multi-Head Attention: 다양한 관점
단일 주의 메커니즘 대신 Transformers는 다음을 사용합니다. h 머리 (머리) 병렬로, 각각 자체 투영 행렬을 갖습니다.
모든 머리에는 차원이 있습니다 d_k = d_{\\text{모델}} / h. 8개의 머리로 전자 d_{\\text{모델}} = 512, 각 머리는 64차원 공간에서 작동합니다.
왜 머리가 더 많아? 각 헤드는 다양한 유형의 관계를 포착할 수 있습니다. 한 헤드는 구문에 초점을 맞추고, 다른 헤드는 의미론에, 다른 헤드는 상호 참조에 중점을 둘 수 있습니다.
import numpy as np
def multi_head_attention(X, n_heads, d_model):
"""Multi-Head Attention implementazione semplificata."""
d_k = d_model // n_heads
seq_len = X.shape[0]
# Proiezioni per ogni testa
heads_output = []
all_weights = []
for h in range(n_heads):
W_Q = np.random.randn(d_model, d_k) * 0.1
W_K = np.random.randn(d_model, d_k) * 0.1
W_V = np.random.randn(d_model, d_k) * 0.1
Q = X @ W_Q
K = X @ W_K
V = X @ W_V
# Scaled dot-product attention
scores = Q @ K.T / np.sqrt(d_k)
weights = softmax(scores)
head_out = weights @ V
heads_output.append(head_out)
all_weights.append(weights)
# Concatena le teste
concat = np.concatenate(heads_output, axis=-1) # (seq_len, d_model)
# Proiezione output
W_O = np.random.randn(d_model, d_model) * 0.1
output = concat @ W_O
return output, all_weights
np.random.seed(42)
seq_len, d_model, n_heads = 6, 16, 4
X = np.random.randn(seq_len, d_model)
output, weights = multi_head_attention(X, n_heads, d_model)
print(f"Input: {X.shape}, Output: {output.shape}")
print(f"Numero teste: {n_heads}, d_k per testa: {d_model // n_heads}")
위치 인코딩: 반복되지 않는 순서
주의는 순열 불변: 토큰의 순서를 구분하지 않습니다. 에 대한 위치 정보를 추가하면 위치 인코딩 기반 정현파 함수에 대해:
왜 사인과 코사인인가? 왜 PE{pos+k} 다음과 같이 표현될 수 있다 선형 변환 체육{pos}, 모델이 다음을 수행할 수 있도록 합니다. 고정된 상대 거리를 "보는" 방법을 쉽게 배울 수 있습니다.
import numpy as np
def positional_encoding(max_len, d_model):
"""Sinusoidal Positional Encoding."""
PE = np.zeros((max_len, d_model))
position = np.arange(max_len)[:, np.newaxis]
div_term = np.exp(np.arange(0, d_model, 2) * -(np.log(10000.0) / d_model))
PE[:, 0::2] = np.sin(position * div_term) # Indici pari: seno
PE[:, 1::2] = np.cos(position * div_term) # Indici dispari: coseno
return PE
# Genera positional encoding
max_len, d_model = 100, 64
PE = positional_encoding(max_len, d_model)
print(f"PE shape: {PE.shape}")
print(f"PE[0, :8]: {np.round(PE[0, :8], 4)}")
print(f"PE[1, :8]: {np.round(PE[1, :8], 4)}")
# L'embedding finale e: token_embedding + positional_encoding
token_embedding = np.random.randn(10, d_model) # 10 token
input_with_position = token_embedding + PE[:10]
print(f"\nEmbedding + PE shape: {input_with_position.shape}")
레이어 정규화 및 잔여 연결
Transformer의 각 하위 계층은 다음을 사용합니다. 잔여 연결 e 레이어 정규화:
레이어 정규화는 기능 차원을 따라 정규화됩니다.
어디 \\mu e \\시그마 에 대해 계산됩니다 각 샘플, e \\감마, \\베타 학습 가능한 매개변수입니다.
요약
기억해야 할 핵심 사항
- 주목: \\text{softmax}(QK^T / \\sqrt{d_k}) V - 토큰 간의 가중치 유사성
- 스케일링 \\sqrt{d_k}: 소프트맥스의 포화를 방지합니다.
- 멀티 헤드: h 병렬의 헤드는 서로 다른 관계를 포착합니다.
- 위치 인코딩: 사인/코사인 순차 순서 추가
- 잔여 + LayerNorm: 심층 네트워크 훈련 안정화
- 전체 아키텍처는 선형 대수 및 소프트맥스 연산으로 구성됩니다.
다음 기사에서: 우리는 다음을 탐구할 것이다. 데이터 증대 전자 합성 데이터 생성 기술. SMOTE, Mixup, 이미지 및 텍스트 확대, 증강이 정말로 도움이 될 때.







