Track II · DL Fundamentals · 06/07

Attention: query·key·valueAttention: query, key, value

Attention을 미분 가능한 사전 조회로 이해하고, scaled dot-product attention의 각 요소 — QKV 투영, √d로 나누는 이유(내적의 분산), softmax 포화, causal mask, multi-head — 를 유도하고 NumPy로 구현한다. O(n²) 비용이 어디서 오는지 설명할 수 있게 된다.Understand attention as a differentiable dictionary lookup, and derive and implement in NumPy each part of scaled dot-product attention — the QKV projections, why we divide by √d (the variance of a dot product), softmax saturation, the causal mask, multi-head. You will be able to explain where the O(n²) cost comes from.

35 분min attention · self-attention · scaled dot-product · softmax · causal mask · multi-head 먼저 볼 것:Before this: 순환 신경망과 LSTMRecurrent networks and LSTM, 확률로 보는 손실Losses through probability

The last lesson ended with the bottleneck of an RNN having to compress the whole past into one fixed-size vector. Bahdanau et al. (2015) had a simple fix: don’t compress — keep every past state, and each time pull out what is needed as a weighted sum. Attention is the generalisation of this “pulling out”, and the Transformer (2017) did away with recurrence altogether and processed sequences with attention alone. This lesson takes that one operation completely apart.

A soft dictionary lookup

Consider a Python dictionary lookup d[q]. Among the stored keys it finds the one exactly equal to the query and returns its value. To make this differentiable, replace the 0–1 judgement “equal / not equal” with a continuous similarity, and instead of picking one, mix them in proportion to similarity.

αi=exp⁡(s(q,ki))∑jexp⁡(s(q,kj)),output=∑iαi vi\alpha_i = \frac{\exp(s(q, k_i))}{\sum_j \exp(s(q, k_j))}, \qquad \text{output} = \sum_i \alpha_i\, v_i

Using the inner product q⊤kiq^\top k_i as the similarity ss gives dot-product attention. The weights α\alpha form a probability distribution (non-negative, summing to 1), so the output is a convex combination of the values — a point inside the polygon the values span. When the similarities differ a lot, softmax concentrates on one and it approaches a hard lookup; when they differ little, it approaches the average.

지난 레슨은 RNN이 과거 전체를 고정 크기 벡터 하나에 압축해야 한다는 병목으로 끝났다. Bahdanau et al.(2015)의 해법은 단순했다. 압축하지 말고 과거의 모든 상태를 남겨 두고, 매번 필요한 것을 가중합으로 꺼내 쓰자. 이 “꺼내 쓰기”를 일반화한 것이 attention이고, Transformer(2017)는 순환을 아예 없애고 attention만으로 시퀀스를 처리했다. 이 레슨은 그 연산 하나를 완전히 해부한다.

부드러운 사전 조회

파이썬 딕셔너리 조회 d[q]를 생각하자. 저장된 key들 중 query와 정확히 같은 것을 찾아 그 value를 돌려준다. 이것을 미분 가능하게 만들려면 “같다/다르다”의 0–1 판정을 연속적인 유사도로 바꾸고, 하나를 고르는 대신 유사도에 비례해 섞으면 된다.

αi=exp⁡(s(q,ki))∑jexp⁡(s(q,kj)),output=∑iαi vi\alpha_i = \frac{\exp(s(q, k_i))}{\sum_j \exp(s(q, k_j))}, \qquad \text{output} = \sum_i \alpha_i\, v_i

유사도 ss로 내적 q⊤kiq^\top k_i를 쓰면 dot-product attention 이다. 가중치 α\alpha는 확률분포(합 1, 비음수)이므로 출력은 value들의 볼록 결합, 즉 value들이 만드는 다각형 안의 한 점이다. 유사도의 차이가 크면 softmax가 하나에 몰려 hard lookup에 가까워지고, 작으면 평균에 가까워진다.

query·key 공간 (끌어서 이동)query·key space (drag to move)
value 공간과 출력value space and output Σ αi vi
softmax 엔트로피entropy – / 최대max log 4 = 1.386 max α –
Drag the purple query to point in the same direction as one of the keys. The larger a key's dot product q·k, the larger its softmax weight α, and the output (★) is pulled towards that key's value. Lower τ or make q longer and the distribution sharpens into what is effectively a hard lookup that picks one; raise τ and the output approaches the average of all values. Dividing by √d when the dimension d is large is exactly this τ = √d adjustment. 보라색 query를 끌어 어떤 key와 같은 방향으로 가져가 보세요. 내적 q·k가 큰 key일수록 softmax 가중치 α가 커지고, 출력(★)이 그 key의 value 쪽으로 끌려간다. τ를 낮추거나 q를 길게 만들면 분포가 뾰족해져 사실상 하나만 고르는 hard lookup이 되고, τ를 높이면 모든 value의 평균에 가까워진다. 차원 d가 클 때 1/√d로 나누는 것이 바로 이 τ = √d 조절이다.

Where do query, key and value come from?

In self-attention all three are made from the same input sequence X∈Rn×dmodelX \in \mathbb{R}^{n\times d_{\text{model}}} by learned linear projections.

Q=XWQ,K=XWK,V=XWV,Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk)VQ = XW_Q,\quad K = XW_K,\quad V = XW_V, \qquad \operatorname{Attention}(Q,K,V) = \operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V

One token plays three roles. The query is “what I am looking for”, the key is “what I advertise to other tokens”, and the value is “what I hand over if someone picks me”. Because the three are separated, “where to look” (QK) and “what to fetch” (V) are learned independently. When the query comes from a different sequence than the keys/values — as when a decoder looks at an encoder — it is cross-attention.

Row ii of the n×nn\times n matrix A=softmax⁡(QK⊤/dk)A = \operatorname{softmax}(QK^\top/\sqrt{d_k}) is token ii‘s weight distribution. Each row of the output AVAV is a weighted sum of the value rows. In other words, attention computes a fresh input-dependent mixing matrix every time and multiplies by it. Convolution also mixes neighbours, but its weights are constants determined only by relative position. In attention the mixing proportions themselves are determined by content.

Why divide by √d?

Suppose the components of q,k∈Rdq, k \in \mathbb{R}^{d} are independent with mean 0 and variance 1 (roughly true right after initialisation). Then

E[q⊤k]=∑i=1dE[qi] E[ki]=0,Var⁡(q⊤k)=∑i=1dVar⁡(qiki)=∑i=1dE[qi2] E[ki2]=d\mathbb{E}[q^\top k] = \sum_{i=1}^{d}\mathbb{E}[q_i]\,\mathbb{E}[k_i] = 0,\qquad \operatorname{Var}(q^\top k) = \sum_{i=1}^{d} \operatorname{Var}(q_i k_i) = \sum_{i=1}^d \mathbb{E}[q_i^2]\,\mathbb{E}[k_i^2] = d

The standard deviation of the dot product grows as d\sqrt d. With dk=128d_k = 128 the logits have a standard deviation of about 11, and a softmax over such logits almost always concentrates on one entry (one-hot). The problem is the gradient there. The Jacobian of softmax is

∂α∂z=diag⁡(α)−αα⊤\frac{\partial \alpha}{\partial z} = \operatorname{diag}(\alpha) - \alpha\alpha^\top

and when α\alpha is one-hot this matrix is 0 (αi(1−αi)=0\alpha_i(1 - \alpha_i) = 0, αiαj=0\alpha_i\alpha_j = 0). No gradient flows through a saturated softmax, so early in training “where to look” cannot change. Dividing the scores by dk\sqrt{d_k} brings the variance back to 1 and the problem goes away. It is the same logic as the variance-preserving initialisation of the previous lessons, and amounts to fixing the temperature τ\tau in the figure above at dk\sqrt{d_k}.

NumPy Scaled dot-product attention and the causal mask
import numpy as np
rng = np.random.default_rng(0)

def softmax(z, axis=-1):
    z = z - z.max(axis=axis, keepdims=True)          # numerical stability (result unchanged)
    e = np.exp(z)
    return e / e.sum(axis=axis, keepdims=True)

def attention(Q, K, V, mask=None):
    """Q: (..., n_q, d), K: (..., n_k, d), V: (..., n_k, d_v). mask: True = may attend"""
    d = Q.shape[-1]
    scores = Q @ np.swapaxes(K, -1, -2) / np.sqrt(d)  # (..., n_q, n_k)
    if mask is not None:
        scores = np.where(mask, scores, -np.inf)      # blocked cells get -inf → softmax 0
    A = softmax(scores)
    return A @ V, A

n, d = 5, 8
X = rng.normal(size=(n, d))
Wq, Wk, Wv = (rng.normal(size=(d, d)) / np.sqrt(d) for _ in range(3))
causal = np.tril(np.ones((n, n), dtype=bool))         # i sees only j ≤ i
out, A = attention(X @ Wq, X @ Wk, X @ Wv, causal)
print("attention weights (causal):\n", np.round(A, 2))
print("row sums:", A.sum(-1), " output shape:", out.shape)

# check causality: changing the last token leaves earlier positions' outputs unchanged
X2 = X.copy(); X2[-1] += 10
out2, _ = attention(X2 @ Wq, X2 @ Wk, X2 @ Wv, causal)
print("last token changed → output change per position:", np.round(np.abs(out2 - out).max(-1), 3))
 
NumPy The effect of √d: softmax entropy as the dimension grows
# why divide by √d: the dot product of q, k with N(0,1) components has variance d
n_keys, trials = 32, 400
print(f"{'d':>5} | {'std(q·k)':>8} | no scaling: entropy  max α | /√d: entropy  max α")
for d in [4, 16, 64, 256, 1024]:
    q = rng.normal(size=(trials, 1, d))
    k = rng.normal(size=(trials, n_keys, d))
    s = (q @ np.swapaxes(k, -1, -2))[:, 0, :]       # (trials, n_keys)
    def stats(z):
        p = softmax(z)
        H = -(p * np.log(p + 1e-30)).sum(-1).mean()
        return H, p.max(-1).mean()
    H0, m0 = stats(s)
    H1, m1 = stats(s / np.sqrt(d))
    print(f"{d:5d} | {s.std():8.2f} | {H0:19.3f} {m0:6.3f} | {H1:13.3f} {m1:6.3f}")
print(f"entropy of the uniform distribution = log {n_keys} = {np.log(n_keys):.3f}")

# a saturated softmax kills the gradient: ∂p/∂z = diag(p) − p pᵀ
for scale in [1, 4, 16, 64]:
    norms, maxp = [], []
    for _ in range(200):
        p = softmax(rng.normal(size=n_keys) * scale)
        norms.append(np.linalg.norm(np.diag(p) - np.outer(p, p)))
        maxp.append(p.max())
    print(f"logit std {scale:2d}: mean max α = {np.mean(maxp):.3f}, median Jacobian norm = {np.median(norms):.1e}")
 

Without scaling, as dd grows the entropy goes to 0 and max α to 1. With /d/\sqrt d the same distribution holds regardless of dd. The Jacobian norm is largest around a logit standard deviation of 4 and drops sharply towards 0 beyond 16.

확인 문제Check yourself

In a head with d_k = 64, suppose the components of q and k are independent standard normals. Without dividing by √d, what is the standard deviation of the attention logit q·k, roughly?

Var⁡(q⊤k)=dk=64\operatorname{Var}(q^\top k) = d_k = 64, so the standard deviation is 64=8\sqrt{64} = 8. With a logit standard deviation of 8, the largest of 32 keys takes over 80% of the weight on average (the d = 64 row of the table above). Dividing by dk=8\sqrt{d_k} = 8 brings the standard deviation back to 1.

Masks: who can see whom

Adding −∞-\infty to a score before the softmax makes that cell’s weight exactly 0. This is how connectivity is enforced.

  • Causal mask: a language model predicts the next token, so position ii looking at j>ij > i would be peeking at the answer. A lower-triangular matrix blocks it. Thanks to it, a single sequence of length nn trains nn prediction problems in parallel in one forward pass (the decisive difference from an RNN).
  • Padding mask: excludes from the keys the padding tokens used to fill out shorter sequences in a batch.

Multi-head: several relations at once

One head picks one distribution per position, i.e. only one kind of “place to look”. But a token needs to know several relations at once: the token right before it, where the same word appeared earlier, the noun it modifies…. Multi-head attention splits dmodeld_{\text{model}} into hh parts; each head does attention independently in dk=dmodel/hd_k = d_{\text{model}}/h dimensions, and the results are concatenated and mixed by WOW_O.

head⁡j=Attention⁡(XWQ(j),XWK(j),XWV(j)),MHA⁡(X)=[head⁡1;… ;head⁡h] WO\operatorname{head}_j = \operatorname{Attention}(XW_Q^{(j)}, XW_K^{(j)}, XW_V^{(j)}),\qquad \operatorname{MHA}(X) = [\operatorname{head}_1; \dots; \operatorname{head}_h]\,W_O

Since WQ,WK,WV,WOW_Q, W_K, W_V, W_O are all dmodel×dmodeld_{\text{model}}\times d_{\text{model}}, the parameter count is 4dmodel24d_{\text{model}}^2 regardless of hh. The same budget is split into several narrow heads instead of one wide one. The figure below reproduces, with hand-made q and k, typical head patterns observed in real trained models.

Query, key, value는 어디서 오는가

Self-attention 에서는 셋 모두 같은 입력 시퀀스 X∈Rn×dmodelX \in \mathbb{R}^{n\times d_{\text{model}}}에서 학습된 선형 투영으로 만든다.

Q=XWQ,K=XWK,V=XWV,Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk)VQ = XW_Q,\quad K = XW_K,\quad V = XW_V, \qquad \operatorname{Attention}(Q,K,V) = \operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V

토큰 하나가 세 가지 역할을 한다. query는 “내가 찾는 것”, key는 “내가 다른 토큰에게 광고하는 것”, value는 “누가 나를 고르면 건네줄 것”이다. 셋을 분리했기 때문에 “어디를 볼지”(QK)와 “무엇을 가져올지”(V)를 독립적으로 학습한다. 디코더가 인코더를 볼 때처럼 query와 key/value가 다른 시퀀스에서 오면 cross-attention 이다.

n×nn\times n 행렬 A=softmax⁡(QK⊤/dk)A = \operatorname{softmax}(QK^\top/\sqrt{d_k})의 행 ii가 토큰 ii의 가중치 분포다. 출력 AVAV의 각 행은 value 행들의 가중합이다. 즉 attention은 입력에 따라 달라지는 혼합 행렬 을 매번 새로 계산해 곱하는 연산이다. 합성곱도 이웃을 섞지만 그 가중치는 상대 위치로만 정해진 상수다. attention은 섞는 비율 자체가 내용에 따라 정해진다.

왜 √d로 나누는가

q,k∈Rdq, k \in \mathbb{R}^{d}의 성분이 서로 독립이고 평균 0, 분산 1이라고 하자(초기화 직후 대략 그렇다). 그러면

E[q⊤k]=∑i=1dE[qi] E[ki]=0,Var⁡(q⊤k)=∑i=1dVar⁡(qiki)=∑i=1dE[qi2] E[ki2]=d\mathbb{E}[q^\top k] = \sum_{i=1}^{d}\mathbb{E}[q_i]\,\mathbb{E}[k_i] = 0,\qquad \operatorname{Var}(q^\top k) = \sum_{i=1}^{d} \operatorname{Var}(q_i k_i) = \sum_{i=1}^d \mathbb{E}[q_i^2]\,\mathbb{E}[k_i^2] = d

이다. 내적의 표준편차가 d\sqrt d로 자란다. dk=128d_k = 128이면 logit의 표준편차가 약 11이고, 이런 logit에 softmax를 씌우면 거의 항상 하나에 몰린다(one-hot). 문제는 그때의 기울기다. softmax의 야코비안은

∂α∂z=diag⁡(α)−αα⊤\frac{\partial \alpha}{\partial z} = \operatorname{diag}(\alpha) - \alpha\alpha^\top

이고, α\alpha가 one-hot이면 이 행렬이 0이 된다(αi(1−αi)=0\alpha_i(1 - \alpha_i) = 0, αiαj=0\alpha_i\alpha_j = 0). 포화된 softmax로는 기울기가 흐르지 않아, 학습 초기에 “어디를 볼지”를 바꿀 수 없다. 점수를 dk\sqrt{d_k}로 나누면 분산이 다시 1이 되어 이 문제가 사라진다. 지난 레슨들의 분산 보존 초기화와 같은 논리이고, 위 그림의 온도 τ\tau를 dk\sqrt{d_k}로 고정한 것이다.

NumPy scaled dot-product attention과 causal mask
import numpy as np
rng = np.random.default_rng(0)

def softmax(z, axis=-1):
    z = z - z.max(axis=axis, keepdims=True)          # 수치 안정성 (결과는 불변)
    e = np.exp(z)
    return e / e.sum(axis=axis, keepdims=True)

def attention(Q, K, V, mask=None):
    """Q: (..., n_q, d), K: (..., n_k, d), V: (..., n_k, d_v). mask: True = 볼 수 있음"""
    d = Q.shape[-1]
    scores = Q @ np.swapaxes(K, -1, -2) / np.sqrt(d)  # (..., n_q, n_k)
    if mask is not None:
        scores = np.where(mask, scores, -np.inf)      # 못 보는 칸은 -inf → softmax 0
    A = softmax(scores)
    return A @ V, A

n, d = 5, 8
X = rng.normal(size=(n, d))
Wq, Wk, Wv = (rng.normal(size=(d, d)) / np.sqrt(d) for _ in range(3))
causal = np.tril(np.ones((n, n), dtype=bool))         # i는 j ≤ i만 본다
out, A = attention(X @ Wq, X @ Wk, X @ Wv, causal)
print("attention 가중치 (causal):\n", np.round(A, 2))
print("행 합:", A.sum(-1), " 출력 모양:", out.shape)

# 인과성 확인: 마지막 토큰을 바꿔도 앞 위치의 출력은 그대로
X2 = X.copy(); X2[-1] += 10
out2, _ = attention(X2 @ Wq, X2 @ Wk, X2 @ Wv, causal)
print("마지막 토큰 변경 → 위치별 출력 변화:", np.round(np.abs(out2 - out).max(-1), 3))
 
NumPy √d의 효과: 차원이 커질 때 softmax 엔트로피
# 왜 √d로 나누는가: 성분이 N(0,1)인 q, k의 내적은 분산이 d
n_keys, trials = 32, 400
print(f"{'d':>5} | {'std(q·k)':>8} | 스케일 없음: 엔트로피  max α | /√d: 엔트로피  max α")
for d in [4, 16, 64, 256, 1024]:
    q = rng.normal(size=(trials, 1, d))
    k = rng.normal(size=(trials, n_keys, d))
    s = (q @ np.swapaxes(k, -1, -2))[:, 0, :]       # (trials, n_keys)
    def stats(z):
        p = softmax(z)
        H = -(p * np.log(p + 1e-30)).sum(-1).mean()
        return H, p.max(-1).mean()
    H0, m0 = stats(s)
    H1, m1 = stats(s / np.sqrt(d))
    print(f"{d:5d} | {s.std():8.2f} | {H0:18.3f} {m0:6.3f} | {H1:13.3f} {m1:6.3f}")
print(f"균등 분포의 엔트로피 = log {n_keys} = {np.log(n_keys):.3f}")

# softmax가 포화되면 기울기가 사라진다: ∂p/∂z = diag(p) − p pᵀ
for scale in [1, 4, 16, 64]:
    norms, maxp = [], []
    for _ in range(200):
        p = softmax(rng.normal(size=n_keys) * scale)
        norms.append(np.linalg.norm(np.diag(p) - np.outer(p, p)))
        maxp.append(p.max())
    print(f"logit std {scale:2d}: 평균 max α = {np.mean(maxp):.3f}, 야코비안 노름 중앙값 = {np.median(norms):.1e}")
 

스케일링 없이는 dd가 커질수록 엔트로피가 0으로, max α가 1로 간다. /d/\sqrt d를 하면 dd와 무관하게 같은 분포가 유지된다. 야코비안 노름은 logit 표준편차 4 근처에서 가장 크고, 16을 넘으면 급격히 0으로 떨어진다.

확인 문제Check yourself

d_k = 64인 헤드에서 q, k 성분이 독립 표준정규라고 하자. √d로 나누지 않은 attention logit q·k의 표준편차는 대략?

Var⁡(q⊤k)=dk=64\operatorname{Var}(q^\top k) = d_k = 64이므로 표준편차는 64=8\sqrt{64} = 8이다. logit 표준편차 8이면 key 32개 중 가장 큰 것이 평균 80% 넘는 가중치를 가져간다(위 표의 d = 64 행). dk=8\sqrt{d_k} = 8로 나누면 표준편차가 1로 돌아온다.

Mask: 누가 누구를 볼 수 있는가

softmax 전에 점수에 −∞-\infty를 더하면 그 칸의 가중치가 정확히 0이 된다. 이것으로 연결 구조를 강제한다.

  • Causal mask: 언어 모델은 다음 토큰을 예측하므로 위치 ii가 j>ij > i를 보면 정답을 훔쳐보는 것이다. 하삼각 행렬로 막는다. 덕분에 길이 nn의 시퀀스 하나로 nn개의 예측 문제를 한 번의 순전파 로 병렬 학습한다(RNN과 결정적으로 다른 점).
  • Padding mask: 배치 안의 짧은 시퀀스를 채운 패딩 토큰을 key에서 제외한다.

Multi-head: 여러 관계를 동시에

헤드 하나는 위치마다 분포 하나, 즉 한 종류의 “볼 곳”만 고른다. 그런데 한 토큰은 동시에 여러 관계를 알아야 한다. 바로 앞 토큰, 같은 단어가 나왔던 곳, 수식하는 명사…. Multi-head attention 은 dmodeld_{\text{model}}을 hh개로 쪼개 각 헤드가 dk=dmodel/hd_k = d_{\text{model}}/h 차원에서 독립적으로 attention을 하고, 결과를 이어 붙여 WOW_O로 섞는다.

head⁡j=Attention⁡(XWQ(j),XWK(j),XWV(j)),MHA⁡(X)=[head⁡1;… ;head⁡h] WO\operatorname{head}_j = \operatorname{Attention}(XW_Q^{(j)}, XW_K^{(j)}, XW_V^{(j)}),\qquad \operatorname{MHA}(X) = [\operatorname{head}_1; \dots; \operatorname{head}_h]\,W_O

WQ,WK,WV,WOW_Q, W_K, W_V, W_O가 모두 dmodel×dmodeld_{\text{model}}\times d_{\text{model}}이므로 매개변수는 hh와 무관하게 4dmodel24d_{\text{model}}^2이다. 같은 예산을 한 개의 넓은 헤드 대신 여러 좁은 헤드로 나눈 것이다. 아래 그림은 실제 학습된 모델에서 관찰되는 대표적 헤드 패턴들을 손으로 만든 q, k로 재현한 것이다.

Row = query position, column = key position, colour = softmax weight α. Click a row and the strip below shows where in the sentence that query looks. All five heads are patterns built from genuine q·k dot products (explained in the grey text below). Turn off the causal mask and each token also sees the future. Lower β to 0 and any head becomes a uniform average. 행 = query 위치, 열 = key 위치, 색 = softmax 가중치 α. 행을 클릭하면 그 query가 문장의 어디를 보는지 아래 띠에 표시된다. 다섯 헤드 모두 진짜 q·k 내적으로 만든 패턴이다(설명은 아래 회색 글). causal mask를 끄면 각 토큰이 미래도 본다. β를 0으로 내리면 어떤 헤드든 균등 평균이 된다.

Pay attention to the induction head. It is a circuit that predicts B after ”… A B … A”, and it is a composition of two heads. A previous-token head in an earlier layer writes at each position “what was the token before me”; a head in a later layer uses that as its key to find “the position right after an earlier occurrence of the current token”. Olsson et al. (2022) showed that such heads form abruptly at a particular point in training, and that in-context learning ability jumps at the same moment.

NumPy Splitting into heads and the O(n²) cost
# multi-head: split d_model into h parts, attend separately → concatenate, W_o
def multi_head(X, Wq, Wk, Wv, Wo, h, mask=None):
    n, D = X.shape
    dh = D // h
    split = lambda M: M.reshape(n, h, dh).transpose(1, 0, 2)   # (h, n, dh)
    Q, K, V = split(X @ Wq), split(X @ Wk), split(X @ Wv)
    O, A = attention(Q, K, V, mask)                           # each head independent (like a batch dim)
    return O.transpose(1, 0, 2).reshape(n, D) @ Wo, A

n, D = 6, 16
X = rng.normal(size=(n, D))
Wq, Wk, Wv, Wo = (rng.normal(size=(D, D)) / np.sqrt(D) for _ in range(4))
causal = np.tril(np.ones((n, n), dtype=bool))
for h in [1, 2, 4, 8]:
    Y, A = multi_head(X, Wq, Wk, Wv, Wo, h, causal)
    print(f"h={h}: dim per head {D//h:2d}, weight matrix shape {A.shape}, parameters 4·D² = {4*D*D} (independent of h)")

# cost: the n×n score matrix
for n_ctx in [1_000, 8_000, 128_000]:
    print(f"n = {n_ctx:>7,}: one head's score matrix has {n_ctx**2:.1e} elements = {n_ctx**2 * 2 / 2**30:8.2f} GiB (bf16)")
 

Cost: O(n²)

QK⊤QK^\top is an n×nn\times n matrix. Time is O(n2d)O(n^2 d), and materialising it as is also takes O(n2)O(n^2) memory per head. As computed above, at a 128K context one head’s score matrix alone is 30 GiB. FlashAttention (Dao et al., 2022) computes the softmax online block by block and produces exactly the same result without materialising this matrix. Memory becomes O(n)O(n), but the O(n2d)O(n^2 d) compute stays. At short contexts the MLP and projection matrix products dominate compute rather than attention; as the context grows, attention’s share grows (the next lesson counts it precisely).

One more property: without positional information, self-attention is permutation equivariant. Shuffle the order of the input tokens and the output is merely shuffled the same way, because position enters neither the dot products nor the weighted sums. That is why a positional encoding, such as position embeddings or RoPE, is indispensable (Track III, GPT lesson). The causal mask does give some order information, but it is not enough on its own.

PyTorch PyTorch: F.scaled_dot_product_attention 로컬에서 실행run locally (pip install torch)
import math
import torch
import torch.nn.functional as F

B, h, n, dk = 2, 4, 10, 16
q, k, v = (torch.randn(B, h, n, dk) for _ in range(3))

# hand-written
scores = q @ k.transpose(-2, -1) / math.sqrt(dk)
causal = torch.ones(n, n, dtype=torch.bool).tril()
scores = scores.masked_fill(~causal, float("-inf"))
manual = scores.softmax(dim=-1) @ v

# built-in kernel (dispatches to FlashAttention / memory-efficient kernels when possible)
fused = F.scaled_dot_product_attention(q, k, v, is_causal=True)
print(torch.allclose(manual, fused, atol=1e-5))      # True

# module form: includes the projections W_Q, W_K, W_V, W_O
mha = torch.nn.MultiheadAttention(embed_dim=64, num_heads=4, batch_first=True)
x = torch.randn(B, n, 64)
y, attn = mha(x, x, x, attn_mask=~causal)            # here True = "masked out"
print(y.shape, attn.shape)                           # (2, 10, 64) (2, 10, 10) — averaged over heads
 

Summary

  • Attention = a soft dictionary lookup. It takes a weighted average of values using the softmax of query–key similarities. The output is a convex combination of the values.
  • Self-attention makes Q,K,VQ, K, V as different linear projections of the same input, and multiplies by an input-dependent mixing matrix.
  • Var⁡(q⊤k)=d\operatorname{Var}(q^\top k) = d, so dividing by d\sqrt d sets the logit variance to 1. Otherwise the softmax saturates and the gradient vanishes.
  • A causal mask trains next-token prediction at every position in parallel in one forward pass.
  • Multi-head sees several relations at once with the same 4d24d^2 parameters. Cost: O(n2d)O(n^2 d) time, and O(n2)O(n^2) memory in a naive implementation.

유도 헤드(induction head) 를 눈여겨보자. ”… A B … A” 다음에 B를 예측하게 하는 회로로, 두 헤드의 합성이다. 앞 층의 이전 토큰 헤드가 각 위치에 “내 앞 토큰은 무엇이었나”를 써 두면, 뒤 층의 헤드는 그것을 key로 써서 “지금 토큰과 같은 토큰 바로 뒤에 있던 위치”를 찾는다. Olsson et al.(2022)은 이런 헤드가 학습 중 특정 시점에 갑자기 형성되고, 그와 동시에 in-context learning 능력이 뛰어오른다는 것을 보였다.

NumPy multi-head로 쪼개기와 O(n²) 비용
# multi-head: d_model을 h개로 쪼개 각자 attention → 이어 붙여 W_o
def multi_head(X, Wq, Wk, Wv, Wo, h, mask=None):
    n, D = X.shape
    dh = D // h
    split = lambda M: M.reshape(n, h, dh).transpose(1, 0, 2)   # (h, n, dh)
    Q, K, V = split(X @ Wq), split(X @ Wk), split(X @ Wv)
    O, A = attention(Q, K, V, mask)                           # 헤드별로 독립 (배치 차원처럼)
    return O.transpose(1, 0, 2).reshape(n, D) @ Wo, A

n, D = 6, 16
X = rng.normal(size=(n, D))
Wq, Wk, Wv, Wo = (rng.normal(size=(D, D)) / np.sqrt(D) for _ in range(4))
causal = np.tril(np.ones((n, n), dtype=bool))
for h in [1, 2, 4, 8]:
    Y, A = multi_head(X, Wq, Wk, Wv, Wo, h, causal)
    print(f"h={h}: 헤드당 차원 {D//h:2d}, 가중치 행렬 모양 {A.shape}, 매개변수 4·D² = {4*D*D} (h와 무관)")

# 비용: n×n 점수 행렬
for n_ctx in [1_000, 8_000, 128_000]:
    print(f"n = {n_ctx:>7,}: 헤드 하나의 점수 행렬 {n_ctx**2:.1e}개 원소 = {n_ctx**2 * 2 / 2**30:8.2f} GiB (bf16)")
 

비용: O(n²)

QK⊤QK^\top는 n×nn\times n 행렬이다. 시간은 O(n2d)O(n^2 d), 그대로 만들면 메모리도 헤드마다 O(n2)O(n^2)다. 위 계산대로 128K 문맥이면 헤드 하나의 점수 행렬만 30 GiB다. FlashAttention(Dao et al., 2022)은 블록 단위로 softmax를 온라인 계산해 이 행렬을 메모리에 만들지 않고도 정확히 같은 결과를 낸다. 메모리는 O(n)O(n)이 되지만 계산량 O(n2d)O(n^2 d)는 그대로다. 짧은 문맥에서는 attention보다 MLP·투영 행렬곱이 계산을 지배하고, 문맥이 길어질수록 attention 몫이 커진다(다음 레슨에서 정확히 센다).

또 하나의 성질: 위치 정보가 없으면 self-attention은 순열 등변 이다. 입력 토큰의 순서를 섞으면 출력도 같이 섞일 뿐이다. 내적과 가중합 어디에도 위치가 들어가지 않기 때문이다. 그래서 위치 임베딩이나 RoPE 같은 위치 인코딩이 반드시 필요하다(Track III GPT 레슨). causal mask는 순서 정보를 일부 주긴 하지만 그것만으로는 충분하지 않다.

PyTorch PyTorch: F.scaled_dot_product_attention 로컬에서 실행run locally (pip install torch)
import math
import torch
import torch.nn.functional as F

B, h, n, dk = 2, 4, 10, 16
q, k, v = (torch.randn(B, h, n, dk) for _ in range(3))

# 직접 구현
scores = q @ k.transpose(-2, -1) / math.sqrt(dk)
causal = torch.ones(n, n, dtype=torch.bool).tril()
scores = scores.masked_fill(~causal, float("-inf"))
manual = scores.softmax(dim=-1) @ v

# 내장 커널 (가능하면 FlashAttention/메모리 효율 커널로 디스패치)
fused = F.scaled_dot_product_attention(q, k, v, is_causal=True)
print(torch.allclose(manual, fused, atol=1e-5))      # True

# 모듈 형태: 투영 W_Q, W_K, W_V, W_O 포함
mha = torch.nn.MultiheadAttention(embed_dim=64, num_heads=4, batch_first=True)
x = torch.randn(B, n, 64)
y, attn = mha(x, x, x, attn_mask=~causal)            # 여기선 True = "가린다"
print(y.shape, attn.shape)                           # (2, 10, 64) (2, 10, 10) — 헤드 평균
 

정리

  • Attention = 부드러운 사전 조회. query–key 유사도의 softmax로 value를 가중평균한다. 출력은 value들의 볼록 결합이다.
  • Self-attention은 Q,K,VQ, K, V를 같은 입력의 서로 다른 선형 투영으로 만들고, 입력에 따라 달라지는 혼합 행렬을 곱한다.
  • Var⁡(q⊤k)=d\operatorname{Var}(q^\top k) = d이므로 d\sqrt d로 나눠 logit 분산을 1로 맞춘다. 그렇지 않으면 softmax가 포화되어 기울기가 사라진다.
  • Causal mask로 한 번의 순전파에서 모든 위치의 다음 토큰 예측을 병렬 학습한다.
  • Multi-head는 같은 4d24d^2 매개변수로 여러 관계를 동시에 본다. 비용은 시간 O(n2d)O(n^2 d), 순진한 구현에서 메모리 O(n2)O(n^2).

더 읽을거리Further reading