C.W.K.
Stream
Lesson 04 of 10 · published

attention의 핵심 통찰: 모든 쌍에 직접 접근

~20 min · attention, intuition, core-idea

Level 0Token
0 XP0/94 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

트랜스포머의 핵심 통찰은 너무 간단해서 약간 민망할 정도야: 모든 토큰이 다른 모든 토큰에, 거리 상관없이, 직접 attend하게 두자. 순환 없이, convolution window 없이, 순차 상태 없이. 그냥 모든 위치 쌍에 대해 학습된 similarity 함수 하나.

이 한 수가 나머지 전부를 풀어. 위치 간 병렬화가 되는 이유, 긴 의존성에서 gradient가 안 죽는 이유, 같은 아키텍처가 텍스트에서 이미지로 오디오로 단백질 시퀀스로 그대로 옮겨가는 이유 — 다 이거 때문이야.

3줄짜리 핵심

이 공식은 앞으로 트랙 내내 본다. 모양을 외워:

  1. scores = Q @ K.T / sqrt(d_k) — 모든 쌍 (i, j)이 similarity score 하나씩 받아.
  2. weights = softmax(scores) — 각 행이 위치들에 대한 확률 분포가 돼.
  3. output = weights @ V — 각 위치의 출력 = 모든 value의 가중합.

matmul 셋 + softmax. 메커니즘 전체가 이거야. multi-head, positional encoding, KV-cache, GQA, RoPE, Flash Attention 같은 건 전부 이 위에 얹은 엔지니어링 광택이고.

비용은 어디 있나

"모든 토큰이 모든 토큰을 본다"의 가격은 (n × n) score 행렬이야. 시퀀스 길이에 대해 O(n²) 연산량 + 메모리. 토큰 수천 개까진 싸. 1M 토큰 가면 안 싸지지. 그래서 attention을 효율적으로 만드는 sub-industry가 있는 거고(Track 4에서 다뤄).

Code

Self-attention from scratch — no PyTorch nn modules·python
import numpy as np

def self_attention(X, W_q, W_k, W_v):
    # X: (n, d_model); W_*: (d_model, d_k or d_v)
    Q = X @ W_q
    K = X @ W_k
    V = X @ W_v
    d_k = K.shape[-1]
    scores = Q @ K.T / np.sqrt(d_k)         # (n, n)
    weights = softmax(scores, axis=-1)       # row-wise softmax
    return weights @ V                       # (n, d_v)

def softmax(x, axis):
    x = x - x.max(axis=axis, keepdims=True)  # numerical stability
    e = np.exp(x)
    return e / e.sum(axis=axis, keepdims=True)
Path length comparison·text
RNN:        position 1 ----step----step----step--... ----> position n   (depth n)
CNN k=3:    position 1 -conv-conv-conv-... -> position n               (depth log_k n)
Attention:  position 1 -------- direct weight --------> position n      (depth 1)

External links

Exercise

NumPy로 self_attention(X) 처음부터 구현해 봐. 모든 스텝에 shape 주석 달고. 같은 Q/K/V를 torch.nn.functional.scaled_dot_product_attention에 넣어서 결과가 float 정밀도 안에서 일치하는지 확인해. 이 파일 저장해 둬 — Track 4에서 multi-head + causal mask로 확장할 거야.

Progress

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

댓글 0

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

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