C.W.K.
Stream
Lesson 01 of 05 · published

Transformer 가 강한 이유

~14 min · transformer, attention, foundations

Level 0Observer
0 XP0/50 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

Self-attention 은 학습된 database lookup 이야

Self-attention 의 초능력은, 모든 토큰이 다른 모든 토큰을 볼 수 있고, query 마다 어떤 토큰을 얼마나 무게 줄지 결정할 수 있다는 거야. 이전 어떤 sequence architecture 도 이 정도 유연성을 주지 못했어. RNN 은 hidden state 하나로 모든 정보를 짜내야 했고 — fixed-size bottleneck 이라 long-range detail 이 날아갔지. Convolution 은 receptive field 가 고정 — 본질적으로 local. Attention 은 어떤 거리에서도 pairwise 관계를 만들 수 있게 했고, 그 가중치도 토큰 내용에서 runtime 에 계산했어.

메커니즘은 세 텐서의 춤이야. 토큰마다 query Q ("내가 뭘 찾고 있지?"), key K ("내가 뭘 가지고 있지?"), value V ("내가 뭘 출력하지?") 를 계산해. pairwise score Q·Kᵀ/√d_k 가 모든 토큰이 다른 모든 토큰에 얼마나 relevant 한지를 알려줘. softmax 가 그 score 를 분포로 바꾸고. V 를 곱하면 각 위치마다 context-aware 출력이 나와. 전체가 matmul 한 번, softmax 한 번, matmul 한 번이야.

왜 살아남았는지

compute 가 따라잡으면서 attention 을 dominant 하게 만든 세 가지 속성이 있어. 첫째, 학습 시 sequence dimension 따라 완전 parallel — RNN 처럼 토큰 하나씩 순차로 step 안 밟아도 돼. 둘째, multi-head attention 이 여러 관계 패턴을 동시에 학습 — 다른 head 들이 syntax, coreference, 위치, semantics 같은 거에 자연스럽게 specialize 돼. 셋째, residual stream + layer norm 이랑 깔끔하게 compose 돼서 stack 으로 scale: 2017 의 65M Transformer 와 2025 의 2T MoE 가 같은 fundamental block 을 써.

이게 네가 경쟁해야 할 architecture 야. 이 quest 의 모든 alternative 는 attention 이 가진 뭔가 — 보통은 full context 에 대한 정확한 recall — 을 포기하고 attention 이 못하는 뭔가 — 보통은 subquadratic compute 나 constant inference memory — 를 가져가. attention 이 뭘 잘하는지 아는 게 언제 그걸 떠나도 되는지 아는 첫 단계야.

Code

Scaled dot-product attention — 핵심 연산·python
import torch
import torch.nn.functional as F

def attention(Q, K, V, mask=None):
    # Q, K, V: (batch, heads, seq, d_k)
    d_k = Q.size(-1)
    scores = (Q @ K.transpose(-2, -1)) / (d_k ** 0.5)  # (B, H, n, n)
    if mask is not None:
        scores = scores.masked_fill(mask == 0, float('-inf'))
    weights = F.softmax(scores, dim=-1)                 # (B, H, n, n)
    return weights @ V                                  # (B, H, n, d_k)

External links

Exercise

PyTorch 로 scaled dot-product attention 을 처음부터 짜봐. 그리고 random (4, 8, 64, 32) Q/K/V 배치에서 torch.nn.functional.scaled_dot_product_attention 결과랑 일치하는지 확인. 그 다음 sequence length 4096 에서 두 구현 시간 재고 비율 보고해. 핵심은 수식이 같아도 PyTorch fused kernel 이 wall-clock 에서 얼마나 사주는지 직접 느껴보는 거야.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.