
100번 Scaled Dot-Product Attention 한 head 만 계산. Multi-Head Attention 은 차원을 개 head 로 쪼개 각각 attention 을 병렬로 실행한 뒤 다시 붙입니다:
Q, K, V: (L, d)
→ reshape → (L, H, d_h)
→ transpose → (H, L, d_h)
→ attention per head → (H, L, d_h)
→ transpose back → (L, H, d_h)
→ reshape → (L, d)
함수 multi_head_attention(Q, K, V, num_heads) 를 완성하세요.
Q, K, V shape (L, d), 는 num_heads 로 나뉨.(L, d).L, d = Q.shape; H = num_heads; dh = d // H
Qh = Q.reshape(L, H, dh).transpose(1, 0, 2) # (H, L, dh)
Kh = K.reshape(L, H, dh).transpose(1, 0, 2)
Vh = V.reshape(L, H, dh).transpose(1, 0, 2)
scores = Qh @ Kh.transpose(0, 2, 1) / np.sqrt(dh) # (H, L, L)
scores -= scores.max(axis=-1, keepdims=True) # stability
w = np.exp(scores)
w /= w.sum(axis=-1, keepdims=True)
out_h = w @ Vh # (H, L, dh)
return out_h.transpose(1, 0, 2).reshape(L, d)
| # | 이름 | 검증 |
|---|---|---|
| 1 | shape (L, d) | |
| 2 | H=1 → 100번 attention 과 동일 | |
| 3 | H=d → 각 head 가 1차원 | dh=1 |
| 4 | Q=K=V (동일) → 자기 자신 포함한 분포 | |
| 5 | Q, K 분해 후 head 별 결과 합과 일치 | 논리 검증 |
축하합니다. 200개 ML/DL 문제 완주! 🎓
코드를 작성하고 Run 을 눌러보세요.