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.
Using the inner product as the similarity gives dot-product attention. The weights 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 판정을 연속적인 유사도로 바꾸고, 하나를 고르는 대신 유사도에 비례해 섞으면 된다.
유사도 로 내적 를 쓰면 dot-product attention 이다. 가중치 는 확률분포(합 1, 비음수)이므로 출력은 value들의 볼록 결합, 즉 value들이 만드는 다각형 안의 한 점이다. 유사도의 차이가 크면 softmax가 하나에 몰려 hard lookup에 가까워지고, 작으면 평균에 가까워진다.
Where do query, key and value come from?
In self-attention all three are made from the same input sequence by learned linear projections.
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 of the matrix is token ‘s weight distribution. Each row of the output 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 are independent with mean 0 and variance 1 (roughly true right after initialisation). Then
The standard deviation of the dot product grows as . With 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
and when is one-hot this matrix is 0 (, ). No gradient flows through a saturated softmax, so early in training “where to look” cannot change. Dividing the scores by 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 in the figure above at .
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))# 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 grows the entropy goes to 0 and max α to 1. With the same distribution holds regardless of . The Jacobian norm is largest around a logit standard deviation of 4 and drops sharply towards 0 beyond 16.
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?
, so the standard deviation is . 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 brings the standard deviation back to 1.
Masks: who can see whom
Adding 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 looking at would be peeking at the answer. A lower-triangular matrix blocks it. Thanks to it, a single sequence of length trains 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 into parts; each head does attention independently in dimensions, and the results are concatenated and mixed by .
Since are all , the parameter count is regardless of . 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 에서는 셋 모두 같은 입력 시퀀스 에서 학습된 선형 투영으로 만든다.
토큰 하나가 세 가지 역할을 한다. query는 “내가 찾는 것”, key는 “내가 다른 토큰에게 광고하는 것”, value는 “누가 나를 고르면 건네줄 것”이다. 셋을 분리했기 때문에 “어디를 볼지”(QK)와 “무엇을 가져올지”(V)를 독립적으로 학습한다. 디코더가 인코더를 볼 때처럼 query와 key/value가 다른 시퀀스에서 오면 cross-attention 이다.
행렬 의 행 가 토큰 의 가중치 분포다. 출력 의 각 행은 value 행들의 가중합이다. 즉 attention은 입력에 따라 달라지는 혼합 행렬 을 매번 새로 계산해 곱하는 연산이다. 합성곱도 이웃을 섞지만 그 가중치는 상대 위치로만 정해진 상수다. attention은 섞는 비율 자체가 내용에 따라 정해진다.
왜 √d로 나누는가
의 성분이 서로 독립이고 평균 0, 분산 1이라고 하자(초기화 직후 대략 그렇다). 그러면
이다. 내적의 표준편차가 로 자란다. 이면 logit의 표준편차가 약 11이고, 이런 logit에 softmax를 씌우면 거의 항상 하나에 몰린다(one-hot). 문제는 그때의 기울기다. softmax의 야코비안은
이고, 가 one-hot이면 이 행렬이 0이 된다(, ). 포화된 softmax로는 기울기가 흐르지 않아, 학습 초기에 “어디를 볼지”를 바꿀 수 없다. 점수를 로 나누면 분산이 다시 1이 되어 이 문제가 사라진다. 지난 레슨들의 분산 보존 초기화와 같은 논리이고, 위 그림의 온도 를 로 고정한 것이다.
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))# 왜 √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}")스케일링 없이는 가 커질수록 엔트로피가 0으로, max α가 1로 간다. 를 하면 와 무관하게 같은 분포가 유지된다. 야코비안 노름은 logit 표준편차 4 근처에서 가장 크고, 16을 넘으면 급격히 0으로 떨어진다.
d_k = 64인 헤드에서 q, k 성분이 독립 표준정규라고 하자. √d로 나누지 않은 attention logit q·k의 표준편차는 대략?
이므로 표준편차는 이다. logit 표준편차 8이면 key 32개 중 가장 큰 것이 평균 80% 넘는 가중치를 가져간다(위 표의 d = 64 행). 로 나누면 표준편차가 1로 돌아온다.
Mask: 누가 누구를 볼 수 있는가
softmax 전에 점수에 를 더하면 그 칸의 가중치가 정확히 0이 된다. 이것으로 연결 구조를 강제한다.
- Causal mask: 언어 모델은 다음 토큰을 예측하므로 위치 가 를 보면 정답을 훔쳐보는 것이다. 하삼각 행렬로 막는다. 덕분에 길이 의 시퀀스 하나로 개의 예측 문제를 한 번의 순전파 로 병렬 학습한다(RNN과 결정적으로 다른 점).
- Padding mask: 배치 안의 짧은 시퀀스를 채운 패딩 토큰을 key에서 제외한다.
Multi-head: 여러 관계를 동시에
헤드 하나는 위치마다 분포 하나, 즉 한 종류의 “볼 곳”만 고른다. 그런데 한 토큰은 동시에 여러 관계를 알아야 한다. 바로 앞 토큰, 같은 단어가 나왔던 곳, 수식하는 명사…. Multi-head attention 은 을 개로 쪼개 각 헤드가 차원에서 독립적으로 attention을 하고, 결과를 이어 붙여 로 섞는다.
가 모두 이므로 매개변수는 와 무관하게 이다. 같은 예산을 한 개의 넓은 헤드 대신 여러 좁은 헤드로 나눈 것이다. 아래 그림은 실제 학습된 모델에서 관찰되는 대표적 헤드 패턴들을 손으로 만든 q, k로 재현한 것이다.
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.
# 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²)
is an matrix. Time is , and materialising it as is also takes 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 , but the 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.
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 headsSummary
- 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 as different linear projections of the same input, and multiplies by an input-dependent mixing matrix.
- , so dividing by 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 parameters. Cost: time, and memory in a naive implementation.
유도 헤드(induction head) 를 눈여겨보자. ”… A B … A” 다음에 B를 예측하게 하는 회로로, 두 헤드의 합성이다. 앞 층의 이전 토큰 헤드가 각 위치에 “내 앞 토큰은 무엇이었나”를 써 두면, 뒤 층의 헤드는 그것을 key로 써서 “지금 토큰과 같은 토큰 바로 뒤에 있던 위치”를 찾는다. Olsson et al.(2022)은 이런 헤드가 학습 중 특정 시점에 갑자기 형성되고, 그와 동시에 in-context learning 능력이 뛰어오른다는 것을 보였다.
# 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²)
는 행렬이다. 시간은 , 그대로 만들면 메모리도 헤드마다 다. 위 계산대로 128K 문맥이면 헤드 하나의 점수 행렬만 30 GiB다. FlashAttention(Dao et al., 2022)은 블록 단위로 softmax를 온라인 계산해 이 행렬을 메모리에 만들지 않고도 정확히 같은 결과를 낸다. 메모리는 이 되지만 계산량 는 그대로다. 짧은 문맥에서는 attention보다 MLP·투영 행렬곱이 계산을 지배하고, 문맥이 길어질수록 attention 몫이 커진다(다음 레슨에서 정확히 센다).
또 하나의 성질: 위치 정보가 없으면 self-attention은 순열 등변 이다. 입력 토큰의 순서를 섞으면 출력도 같이 섞일 뿐이다. 내적과 가중합 어디에도 위치가 들어가지 않기 때문이다. 그래서 위치 임베딩이나 RoPE 같은 위치 인코딩이 반드시 필요하다(Track III GPT 레슨). causal mask는 순서 정보를 일부 주긴 하지만 그것만으로는 충분하지 않다.
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은 를 같은 입력의 서로 다른 선형 투영으로 만들고, 입력에 따라 달라지는 혼합 행렬을 곱한다.
- 이므로 로 나눠 logit 분산을 1로 맞춘다. 그렇지 않으면 softmax가 포화되어 기울기가 사라진다.
- Causal mask로 한 번의 순전파에서 모든 위치의 다음 토큰 예측을 병렬 학습한다.
- Multi-head는 같은 매개변수로 여러 관계를 동시에 본다. 비용은 시간 , 순진한 구현에서 메모리 .
더 읽을거리Further reading
- Vaswani et al., Attention Is All You Need (NeurIPS, 2017) — scaled dot-product attention과 multi-head attention. √d 스케일링의 근거가 각주에 있다Scaled dot-product attention and multi-head attention. The justification for √d scaling is in a footnote
- Bahdanau, Cho, Bengio, Neural Machine Translation by Jointly Learning to Align and Translate (ICLR, 2015) — 인코더 상태들에 대한 가중합으로서의 attention을 처음 제안First proposed attention as a weighted sum over encoder states
- Olah & Carter, Attention and Augmented Recurrent Neural Networks (Distill, 2016) — attention을 "어디에 초점을 둘지"의 부드러운 선택으로 설명하는 시각적 글A visual essay explaining attention as a soft choice of "where to focus"
- Elhage et al., A Mathematical Framework for Transformer Circuits (Anthropic, 2021) — QK 회로(어디를 볼지)와 OV 회로(무엇을 옮길지)로 헤드를 분해하는 관점The view that decomposes a head into a QK circuit (where to look) and an OV circuit (what to move)
- Olsson et al., In-context Learning and Induction Heads (Anthropic, 2022) — 이 레슨 그림의 "유도 헤드"가 실제 모델에서 어떻게 형성되는지How the "induction head" of this lesson's figure forms in real models
- Dao et al., FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (NeurIPS, 2022) — n×n 행렬을 메모리에 만들지 않고 정확히 같은 attention을 계산하는 방법Computes exactly the same attention without materialising the n×n matrix in memory