A transformer forward pass is a few dozen kinds of operation applied to arrays of shape (B, T, H, D): matrix products, dot products, sums over one axis, elementwise maps broadcast across others. Almost every equation later on this site is one of these operations written compactly. This lesson fixes the three readings we will use everywhere: a matrix is a linear map, a dot product is a projection, and a tensor expression is an index contraction whose shape and cost you can read off before running anything.
Dot products: projection, angle, and the √d
For , . Geometrically, is the signed length of ‘s shadow on the direction of , and the projection of onto the line through is
(Check: the residual is orthogonal to , since .) Cauchy–Schwarz, , is what makes well defined. Dividing out the lengths gives cosine similarity, , the standard similarity for embeddings and retrieval.
An attention logit is a raw dot product , so it mixes alignment () with length. If the entries of and are independent with mean 0 and variance 1,
so logits grow like and the softmax saturates. Scaled dot-product attention divides by to undo exactly this. QK-norm goes further and normalises and , so the logit is mostly a scaled cosine.
A matrix is a linear map
A matrix is the linear map from to , and it is completely determined by where it sends the basis vectors: column of is . Two ways to read :
The row view is what a Linear layer computes per output unit; the column view is the one to picture.
Transformer의 forward pass는 (B, T, H, D) 꼴의 배열에 수십 가지 연산을 적용한 것이다. 행렬곱, 내적, 한 축에 대한 합, 다른 축들로 broadcast되는 원소별 함수. 이 사이트 뒤쪽의 거의 모든 식이 이 연산들을 압축해 쓴 것이다. 이 레슨은 앞으로 계속 쓸 세 가지 읽는 법을 고정한다. 행렬은 선형 사상(linear map) 이고, 내적은 사영(projection) 이며, 텐서 식은 index 축약(contraction) 이라서 실행하기 전에 shape과 비용을 읽어 낼 수 있다.
내적: 사영, 각도, 그리고 √d
에 대해 이다. 기하학적으로 는 가 방향에 드리우는 그림자의 부호 있는 길이이고, 를 지나는 직선으로의 사영은 다음과 같다.
(확인: 잔차 는 와 직교한다. 이기 때문이다.) 코시–슈바르츠 부등식(Cauchy–Schwarz) 덕분에 이 잘 정의된다. 길이를 나눠 없애면 코사인 유사도(cosine similarity) 가 되고, embedding과 검색에서 표준으로 쓰는 유사도다.
attention logit은 날것의 내적 라서 정렬 정도()와 길이가 섞여 있다. , 의 성분이 서로 독립이고 평균 0, 분산 1이면
이므로 logit은 에 비례해 커지고 softmax가 포화된다. scaled dot-product attention이 로 나누는 것은 정확히 이것을 되돌리기 위해서다. QK-norm은 한 걸음 더 나가 , 를 정규화해서 logit을 사실상 배율이 곱해진 코사인으로 만든다.
행렬은 선형 사상이다
행렬 은 에서 으로 가는 선형 사상 이고, 기저 벡터를 어디로 보내는지만 알면 완전히 정해진다. 의 번째 열이 다. 를 읽는 두 가지 방법:
행 관점은 Linear layer가 출력 unit마다 계산하는 것이고, 머릿속에 그릴 때는 열 관점을 쓴다.
Composition is the product. Apply then : , so the matrix of the composite map has entries
That is why matrix multiplication is defined the way it is. It is associative (composition is) but not commutative — rotate-then-shear is not shear-then-rotate, as the figure shows. Associativity has a cost consequence that recurs: for , and a vector , costs multiply-adds while costs . LoRA’s is applied as for this reason, and MLA’s “absorb” trick is the same bracket moved the other way.
A second way to expand the product sums outer products: with the columns of and the rows of ,
a sum of rank-1 matrices. Linear attention’s state is exactly this, built one outer product per token.
Determinant. In 2-D, is the signed area of the parallelogram spanned by the columns — the factor by which scales every area, negative when it flips orientation. Since areas scale successively, . means the columns are dependent: the map squashes the plane onto a line (pick “rank 1”), some nonzero has , and no inverse can undo it. In general rank is the dimension of the column space ; is the dimension of the null space.
Transpose is the adjoint. . When a layer computes and the loss sends back , the signal that reaches is — backprop multiplies by transposes because of this identity (calculus lesson).
Norms: how big, and in which geometry
A norm measures size: with equality only at 0, , and the triangle inequality. The family is , with (sum of magnitudes), (Euclidean) and . In ,
RMSNorm uses , the norm rescaled so it does not grow with width.
Each norm has a dual , and Hölder’s inequality (with ) says the dual of is : is self-dual, and are dual to each other. The maximiser is the steepest-ascent direction under that norm — the first-order Taylor model is decreased fastest by . Change the ruler and the best step changes:
합성이 곧 곱이다. 를 하고 를 하면 이므로 합성 사상의 행렬 성분은
이다. 행렬곱이 이렇게 정의된 이유가 이것이다. 합성이 그렇듯 결합법칙은 성립하지만 교환법칙은 성립하지 않는다. 그림에서 보듯 회전 후 밀림과 밀림 후 회전은 다르다. 결합법칙에는 계속 등장하는 비용 결과가 따른다. , , 벡터 에 대해 는 곱셈-덧셈 번, 는 번이다. LoRA의 를 로 적용하는 이유이고, MLA의 “absorb” 기법은 같은 괄호를 반대로 옮긴 것이다.
곱을 전개하는 두 번째 방법은 외적(outer product) 의 합이다. 를 의 열, 를 의 행이라 하면
즉 rank 1 행렬들의 합이다. linear attention의 상태 가 정확히 이것이고, token마다 외적 하나씩 쌓아 만든다.
행렬식(determinant). 2차원에서 는 두 열이 만드는 평행사변형의 부호 있는 넓이, 즉 가 모든 넓이에 곱하는 배율이다. 방향을 뒤집으면 음수가 된다. 넓이가 차례로 곱해지므로 이다. 이면 열들이 일차종속이다. 사상이 평면을 한 직선으로 누르고(“rank 1”을 골라 보자), 인 0 아닌 가 있으며, 어떤 역사상도 이를 되돌릴 수 없다. 일반적으로 rank는 열공간 의 차원이고 가 영공간(null space)의 차원이다.
전치는 수반(adjoint)이다. . layer가 를 계산하고 손실이 를 돌려보내면 에 도달하는 신호는 다. 역전파가 전치를 곱하는 이유가 이 항등식이다(미분 레슨).
노름: 얼마나 큰가, 어떤 기하로 재는가
노름(norm)은 크기를 잰다. 이고 0에서만 등호, , 그리고 삼각부등식. 노름은 이고 (절댓값의 합), (유클리드), 가 대표적이다. 에서
RMSNorm은 , 즉 폭(width)에 따라 커지지 않도록 다시 스케일한 노름을 쓴다.
모든 노름에는 쌍대 노름(dual norm) 가 있고, 횔더 부등식(Hölder) ()는 의 쌍대가 임을 말한다. 는 자기 자신이 쌍대이고 과 는 서로 쌍대다. 최댓값을 주는 가 그 노름으로 잰 최급상승 방향이다. 1차 테일러 모델 를 가장 빨리 줄이는 것이 다. 자를 바꾸면 최선의 step이 바뀐다.
The closed forms: for , ; for , and ; for , with . For , (plug in to check and ). Adam with its averages switched off () divides by — the row. The Muon lesson repeats this table for matrices, where the spectral norm gives .
Matrix norms. Two matter most. The Frobenius norm treats the matrix as a long vector: . The operator (spectral) norm measures the largest stretch, — the long semi-axis of the amber ellipse in the first figure, i.e. the largest singular value (next lesson). By definition , which gives submultiplicativity : a product of layers can stretch a signal by up to , the root of exploding and vanishing signals in deep nets and RNNs. They compare as .
Tensors and how to read their shapes
Beyond matrices we work with arrays of any rank. The conventions on this site: B batch, T (query) positions, S key positions, H heads, D head dimension, model width C = H·D, vocabulary V, experts E. A PyTorch nn.Linear(in, out) stores its weight as [out, in] and computes y = x @ W.T. Splitting heads is a reshape (B,T,C) → (B,T,H,D) followed by a transpose to (B,H,T,D) — the reshape only reinterprets memory, the transpose changes which axis is contiguous.
einsum names every axis with a letter. Rules: letters shared by inputs are multiplied elementwise; a letter absent from the output is summed; the output order is whatever you write. So 'bhtd,bhsd->bhts' is , i.e. per batch and head. The cost of a two-operand einsum is one multiply-add per combination of all indices, so FLOPs .
Broadcasting makes elementwise ops work between different shapes: align shapes from the right; each pair of sizes must be equal or contain a 1 (a missing axis counts as 1); size-1 axes are stretched without copying.
닫힌 꼴은 다음과 같다. 이면 , 이면 이고 , 이면 에 대해 . 이면 이다(대입해서 , 를 확인해 보자). 이동평균을 끈 Adam()은 를 로 나누므로 줄에 해당한다. Muon 레슨은 이 표를 행렬에 대해 다시 만들고, 거기서는 spectral norm이 를 준다.
행렬 노름. 둘이 가장 중요하다. Frobenius 노름은 행렬을 긴 벡터로 본다. . 연산자(spectral) 노름은 가장 크게 늘이는 배율이다. . 첫 그림의 주황 타원의 긴 반축, 즉 가장 큰 특이값이다(다음 레슨). 정의에서 바로 이고, 여기서 곱에 대한 부등식 가 나온다. 개 layer의 곱은 신호를 최대 배까지 늘일 수 있다. 깊은 망과 RNN에서 신호가 폭발하거나 소실되는 뿌리다. 둘 사이에는 가 성립한다.
텐서와 shape 읽기
행렬을 넘어 임의 차수의 배열을 다룬다. 이 사이트의 관례: B batch, T (query) 위치, S key 위치, H head 수, D head 차원, 모델 폭 C = H·D, 어휘 V, expert 수 E. PyTorch nn.Linear(in, out)은 weight를 [out, in]으로 저장하고 y = x @ W.T를 계산한다. head 나누기는 reshape (B,T,C) → (B,T,H,D) 후 (B,H,T,D)로 transpose하는 것이다. reshape은 메모리를 다르게 해석할 뿐이고 transpose는 어느 축이 연속(contiguous)인지를 바꾼다.
einsum은 모든 축에 글자 이름을 붙인다. 규칙: 입력들이 공유하는 글자는 원소별로 곱하고, 출력에 없는 글자는 합한다. 출력 순서는 쓴 대로다. 그래서 'bhtd,bhsd->bhts'는 , 즉 batch·head마다 이다. 두 피연산자 einsum의 비용은 모든 index 조합마다 곱셈-덧셈 한 번이므로 FLOPs 이다.
Broadcasting은 shape이 다른 배열 사이에서도 원소별 연산이 되게 한다. shape을 오른쪽부터 맞추고, 각 쌍의 크기가 같거나 한쪽이 1이어야 한다(없는 축은 1로 친다). 크기 1인 축은 복사 없이 늘어난다.
Three shape bugs account for most silent errors. (1) (N,) minus (N,1) is an N×N matrix of every pairwise difference — a regression loss computed this way is wrong but runs. (2) Normalising without keepdims=True: on (B,T,V) logits, p / p.sum(-1) divides by a (B,T) array and usually fails; on a square (T,T) attention matrix it runs and divides column by the sum of row . (3) A per-sequence quantity of shape (B,) must become (B,1) before it multiplies per-token log-probs (B,T) — the sequence-level advantage in GRPO is exactly this.
Implementing it
The first block checks every identity above numerically; the second writes multi-head attention, GQA and an MoE combine with einsum and reproduces the broadcasting bugs.
import numpy as np
rng = np.random.default_rng(0)
# 1) a matrix is a linear map: its columns are the images of e1, e2
A = np.array([[1.5, 0.4], [0.5, 1.1]])
B = np.array([[0.0, -1.0], [1.0, 0.0]]) # rotate by 90°
x = np.array([1.0, 0.8])
print("column view Ax == x1*A[:,0] + x2*A[:,1] :", np.allclose(A @ x, x[0]*A[:, 0] + x[1]*A[:, 1]))
print("composition B(Ax) == (BA)x :", np.allclose(B @ (A @ x), (B @ A) @ x))
print("commutes? AB == BA :", np.allclose(A @ B, B @ A))
print("determinant det(BA) == det B · det A :", np.isclose(np.linalg.det(B @ A), np.linalg.det(B) * np.linalg.det(A)))
y = rng.normal(size=2)
print("adjoint (Ax)·y == x·(Aᵀy) :", np.isclose((A @ x) @ y, x @ (A.T @ y)))
P, Q = rng.normal(size=(4, 3)), rng.normal(size=(3, 5))
print("outer sums PQ == Σ_k P[:,k] Q[k,:]ᵀ :", np.allclose(P @ Q, sum(np.outer(P[:, k], Q[k]) for k in range(3))))
# 2) dot products of random vectors grow like √d → scale by 1/√d
print()
for d in [16, 128, 1024]:
q, k = rng.normal(size=(2, 4000, d))
s = (q * k).sum(-1)
print(f"d={d:5d} std(q·k)={s.std():6.2f} √d={np.sqrt(d):6.2f} std(q·k/√d)={(s/np.sqrt(d)).std():.3f}")
# 3) vector norms, their ordering, and Hölder's maximisers
v = rng.normal(size=1000)
n1, n2, ninf = np.abs(v).sum(), np.linalg.norm(v), np.abs(v).max()
print(f"\n‖v‖∞={ninf:.2f} ≤ ‖v‖₂={n2:.2f} ≤ ‖v‖₁={n1:.1f} ≤ √n·‖v‖₂={np.sqrt(v.size)*n2:.1f}")
g = rng.normal(size=5)
print("max g·d over ‖d‖∞≤1 is at sign(g), value ‖g‖₁ :", np.isclose(g @ np.sign(g), np.abs(g).sum()))
print("max g·d over ‖d‖₂≤1 is at g/‖g‖₂, value ‖g‖₂:", np.isclose(g @ (g / np.linalg.norm(g)), np.linalg.norm(g)))
Dd = rng.normal(size=(100000, 5)); Dd /= np.abs(Dd).max(1, keepdims=True) # random points with ‖d‖∞ = 1
print(f"random search over ‖d‖∞=1: best g·d = {(Dd @ g).max():.4f} vs ‖g‖₁ = {np.abs(g).sum():.4f}")
# 4) matrix norms: Frobenius and spectral (power iteration on WᵀW)
W = rng.normal(size=(64, 32)) / np.sqrt(32)
z = rng.normal(size=32)
for _ in range(300):
z = W.T @ (W @ z)
z /= np.linalg.norm(z)
sv = np.linalg.svd(W, compute_uv=False)
print(f"\nspectral ‖W‖₂ : power iteration {np.linalg.norm(W @ z):.4f} SVD σ_max {sv[0]:.4f}")
print(f"Frobenius ‖W‖_F = {np.linalg.norm(W):.4f} √(Σσ²) = {np.sqrt((sv**2).sum()):.4f}")
print(f"‖W‖₂ ≤ ‖W‖_F ≤ √rank·‖W‖₂ : {sv[0]:.2f} ≤ {np.linalg.norm(W):.2f} ≤ {np.sqrt(32)*sv[0]:.2f}")
X = rng.normal(size=(32, 2000))
gain = np.linalg.norm(W @ X, axis=0) / np.linalg.norm(X, axis=0)
print(f"max ‖Wx‖/‖x‖ over 2000 random x: {gain.max():.4f} (never above σ_max)")B, T, H, D = 2, 6, 4, 8
C = H * D
# attention with explicit shapes: (B,T,C) → (B,T,H,D) → (B,H,T,D)
x = rng.normal(size=(B, T, C))
Wq, Wk, Wv = rng.normal(size=(3, C, C)) / np.sqrt(C) # PyTorch layout [out, in]
def heads(z): # (B,T,C) → (B,H,T,D)
return z.reshape(B, T, H, D).transpose(0, 2, 1, 3)
q = heads(np.einsum('btc,oc->bto', x, Wq)) # == x @ Wq.T
k = heads(np.einsum('btc,oc->bto', x, Wk))
v = heads(np.einsum('btc,oc->bto', x, Wv))
s = np.einsum('bhtd,bhsd->bhts', q, k) / np.sqrt(D) # sum over d
s = s + np.triu(np.full((T, T), -np.inf), k=1) # (T,S) mask broadcast over (B,H)
p = np.exp(s - s.max(-1, keepdims=True))
p = p / p.sum(-1, keepdims=True) # keepdims: (B,H,T,1)
o = np.einsum('bhts,bhsd->bhtd', p, v)
y = o.transpose(0, 2, 1, 3).reshape(B, T, C) # merge heads back
ref = (q @ k.swapaxes(-1, -2)) / np.sqrt(D)
print("einsum scores == matmul :", np.allclose(np.einsum('bhtd,bhsd->bhts', q, k) / np.sqrt(D), ref))
print("rows of p sum to 1 :", np.allclose(p.sum(-1), 1), "| shapes q", q.shape, "p", p.shape, "y", y.shape)
# GQA: 4 query heads share 2 KV heads (r = 2 queries per KV head) — broadcasting instead of copying
G, R = 2, H // 2
kg = rng.normal(size=(B, G, T, D))
qg = q.reshape(B, G, R, T, D)
s_gqa = np.einsum('bgrtd,bgsd->bgrts', qg, kg)
s_rep = np.einsum('bhtd,bhsd->bhts', q, np.repeat(kg, R, axis=1)).reshape(B, G, R, T, T)
print("GQA einsum == repeat_kv :", np.allclose(s_gqa, s_rep))
# MoE combine: each token mixes its top-k expert outputs with gate weights
N, E, K, Dm = 5, 8, 2, 3
logits = rng.normal(size=(N, E))
top = np.argsort(-logits, axis=1)[:, :K] # (N,K) expert ids
gates = np.take_along_axis(logits, top, 1)
gates = np.exp(gates) / np.exp(gates).sum(1, keepdims=True)
expert_out = rng.normal(size=(N, K, Dm)) # outputs of the chosen experts
mix = np.einsum('nk,nkd->nd', gates, expert_out)
print("MoE combine == loop :", np.allclose(mix, np.stack([sum(gates[n, j] * expert_out[n, j] for j in range(K)) for n in range(N)])))
# Broadcasting pitfalls
y_true = rng.normal(size=8) # (N,)
y_pred = rng.normal(size=(8, 1)) # (N,1) — e.g. the output of Linear(…, 1)
bad = ((y_true - y_pred) ** 2).mean() # (N,) - (N,1) → (N,N): every pair!
good = ((y_true - y_pred[:, 0]) ** 2).mean()
print(f"\nMSE with shape bug {bad:.3f} vs correct {good:.3f} (y_true - y_pred).shape = {(y_true - y_pred).shape}")
adv = rng.normal(size=4) # one advantage per sequence (B,)
logp = rng.normal(size=(4, 16)) # per-token log-probs (B,T)
try:
_ = adv * logp
except ValueError as e:
print("(B,) * (B,T) →", e)
print("(B,1) * (B,T) →", (adv[:, None] * logp).shape)Queries have shape (B=4, H=32, T=2048, D=128) and keys (4, 32, 2048, 128). What does einsum('bhtd,bhsd->bhts', q, k) cost?
Every combination of all five indices costs one multiply-add, so FLOPs . The factor is the quadratic cost of attention; the output alone, scores, is about 0.5 G elements (1 GB in bf16), which is why FlashAttention never materialises it.
Under which norm on the step d is the steepest-descent direction −sign(g), the direction Adam takes when its moving averages are switched off?
is attained at the corner with value (the dual of is ). With it would be ; with it would move only the largest coordinate.
Summary
- A matrix is the linear map whose columns are the images of the basis vectors; products are compositions, associative but not commutative, and bracketing changes cost.
- ; random dot products scale like , hence in attention.
- Norms are rulers. The steepest direction depends on the ruler: , ; for matrices, Frobenius vs spectral.
- is the largest stretch and is submultiplicative, which bounds how products of layers amplify signals.
- Read a tensor expression as an einsum: summed letters, batch letters, cost . Broadcast from the right, and watch
(N,)vs(N,1).
Where this is used
- Attention — and the variance argument above; Transformer —
(B,T,C)↔(B,H,T,D). - GPT from scratch — every shape of a forward pass, written out.
- Attention & KV: MHA → GQA → MLA — GQA by broadcasting, MLA’s absorb (moving the bracket) with einsum.
- MoE anatomy — gates × expert outputs, the combine einsum; Linear attention & SSMs — state as a sum of outer products.
- Optimizers and Muon — gradient clipping by global ℓ₂ norm, sign descent as ℓ∞ steepest descent, spectral-norm steepest descent.
- Stability components — RMSNorm, QK-norm (cosine-like logits).
- Sequence vs token aggregation — broadcasting a
(B,1)advantage over(B,T)tokens with masks. - Next: eigenvalues, SVD and low rank.
조용한 오류의 대부분은 세 가지 shape 버그에서 나온다. (1) (N,)에서 (N,1)을 빼면 모든 쌍의 차이로 된 N×N 행렬이 나온다. 이렇게 계산한 회귀 손실은 틀렸지만 잘 돌아간다. (2) keepdims=True 없이 정규화하기. (B,T,V) logit에서 p / p.sum(-1)은 (B,T) 배열로 나누게 되어 대개 에러가 나지만, 정사각 (T,T) attention 행렬에서는 그대로 돌아가면서 열 를 행 의 합으로 나눈다. (3) (B,) 꼴의 sequence 단위 값은 token 단위 log-prob (B,T)에 곱하기 전에 (B,1)이 되어야 한다. GRPO의 sequence 단위 advantage가 정확히 이 경우다.
직접 구현하기
첫 블록은 위의 항등식을 모두 수치로 확인하고, 두 번째 블록은 multi-head attention, GQA, MoE 결합을 einsum으로 쓰고 broadcasting 버그를 재현한다.
import numpy as np
rng = np.random.default_rng(0)
# 1) 행렬은 선형 사상: 열이 곧 e1, e2의 상
A = np.array([[1.5, 0.4], [0.5, 1.1]])
B = np.array([[0.0, -1.0], [1.0, 0.0]]) # 90° 회전
x = np.array([1.0, 0.8])
print("열 관점 Ax == x1*A[:,0] + x2*A[:,1] :", np.allclose(A @ x, x[0]*A[:, 0] + x[1]*A[:, 1]))
print("합성 B(Ax) == (BA)x :", np.allclose(B @ (A @ x), (B @ A) @ x))
print("교환? AB == BA :", np.allclose(A @ B, B @ A))
print("행렬식 det(BA) == det B · det A :", np.isclose(np.linalg.det(B @ A), np.linalg.det(B) * np.linalg.det(A)))
y = rng.normal(size=2)
print("수반 (Ax)·y == x·(Aᵀy) :", np.isclose((A @ x) @ y, x @ (A.T @ y)))
P, Q = rng.normal(size=(4, 3)), rng.normal(size=(3, 5))
print("외적의 합 PQ == Σ_k P[:,k] Q[k,:]ᵀ :", np.allclose(P @ Q, sum(np.outer(P[:, k], Q[k]) for k in range(3))))
# 2) 무작위 벡터의 내적은 √d 배로 커진다 → 1/√d 로 스케일
print()
for d in [16, 128, 1024]:
q, k = rng.normal(size=(2, 4000, d))
s = (q * k).sum(-1)
print(f"d={d:5d} std(q·k)={s.std():6.2f} √d={np.sqrt(d):6.2f} std(q·k/√d)={(s/np.sqrt(d)).std():.3f}")
# 3) 벡터 노름의 순서와 횔더 부등식의 최대점
v = rng.normal(size=1000)
n1, n2, ninf = np.abs(v).sum(), np.linalg.norm(v), np.abs(v).max()
print(f"\n‖v‖∞={ninf:.2f} ≤ ‖v‖₂={n2:.2f} ≤ ‖v‖₁={n1:.1f} ≤ √n·‖v‖₂={np.sqrt(v.size)*n2:.1f}")
g = rng.normal(size=5)
print("‖d‖∞≤1 에서 g·d 최대는 sign(g), 값은 ‖g‖₁ :", np.isclose(g @ np.sign(g), np.abs(g).sum()))
print("‖d‖₂≤1 에서 g·d 최대는 g/‖g‖₂, 값은 ‖g‖₂:", np.isclose(g @ (g / np.linalg.norm(g)), np.linalg.norm(g)))
Dd = rng.normal(size=(100000, 5)); Dd /= np.abs(Dd).max(1, keepdims=True) # ‖d‖∞ = 1 인 무작위 점
print(f"‖d‖∞=1 무작위 탐색: 최선의 g·d = {(Dd @ g).max():.4f} vs ‖g‖₁ = {np.abs(g).sum():.4f}")
# 4) 행렬 노름: Frobenius 와 spectral (WᵀW 에 power iteration)
W = rng.normal(size=(64, 32)) / np.sqrt(32)
z = rng.normal(size=32)
for _ in range(300):
z = W.T @ (W @ z)
z /= np.linalg.norm(z)
sv = np.linalg.svd(W, compute_uv=False)
print(f"\nspectral ‖W‖₂ : power iteration {np.linalg.norm(W @ z):.4f} SVD σ_max {sv[0]:.4f}")
print(f"Frobenius ‖W‖_F = {np.linalg.norm(W):.4f} √(Σσ²) = {np.sqrt((sv**2).sum()):.4f}")
print(f"‖W‖₂ ≤ ‖W‖_F ≤ √rank·‖W‖₂ : {sv[0]:.2f} ≤ {np.linalg.norm(W):.2f} ≤ {np.sqrt(32)*sv[0]:.2f}")
X = rng.normal(size=(32, 2000))
gain = np.linalg.norm(W @ X, axis=0) / np.linalg.norm(X, axis=0)
print(f"무작위 x 2000개에서 max ‖Wx‖/‖x‖: {gain.max():.4f} (σ_max를 넘지 않는다)")B, T, H, D = 2, 6, 4, 8
C = H * D
# shape을 명시한 attention: (B,T,C) → (B,T,H,D) → (B,H,T,D)
x = rng.normal(size=(B, T, C))
Wq, Wk, Wv = rng.normal(size=(3, C, C)) / np.sqrt(C) # PyTorch 배치 [out, in]
def heads(z): # (B,T,C) → (B,H,T,D)
return z.reshape(B, T, H, D).transpose(0, 2, 1, 3)
q = heads(np.einsum('btc,oc->bto', x, Wq)) # == x @ Wq.T
k = heads(np.einsum('btc,oc->bto', x, Wk))
v = heads(np.einsum('btc,oc->bto', x, Wv))
s = np.einsum('bhtd,bhsd->bhts', q, k) / np.sqrt(D) # d 에 대해 합
s = s + np.triu(np.full((T, T), -np.inf), k=1) # (T,S) mask 가 (B,H) 로 broadcast
p = np.exp(s - s.max(-1, keepdims=True))
p = p / p.sum(-1, keepdims=True) # keepdims: (B,H,T,1)
o = np.einsum('bhts,bhsd->bhtd', p, v)
y = o.transpose(0, 2, 1, 3).reshape(B, T, C) # head 를 다시 합친다
ref = (q @ k.swapaxes(-1, -2)) / np.sqrt(D)
print("einsum 점수 == matmul :", np.allclose(np.einsum('bhtd,bhsd->bhts', q, k) / np.sqrt(D), ref))
print("p 의 각 행 합 = 1 :", np.allclose(p.sum(-1), 1), "| shapes q", q.shape, "p", p.shape, "y", y.shape)
# GQA: query head 4개가 KV head 2개를 공유 (KV head 당 r = 2) — 복사 대신 broadcasting
G, R = 2, H // 2
kg = rng.normal(size=(B, G, T, D))
qg = q.reshape(B, G, R, T, D)
s_gqa = np.einsum('bgrtd,bgsd->bgrts', qg, kg)
s_rep = np.einsum('bhtd,bhsd->bhts', q, np.repeat(kg, R, axis=1)).reshape(B, G, R, T, T)
print("GQA einsum == repeat_kv :", np.allclose(s_gqa, s_rep))
# MoE 결합: token 마다 top-k expert 출력을 gate 가중치로 섞는다
N, E, K, Dm = 5, 8, 2, 3
logits = rng.normal(size=(N, E))
top = np.argsort(-logits, axis=1)[:, :K] # (N,K) expert 번호
gates = np.take_along_axis(logits, top, 1)
gates = np.exp(gates) / np.exp(gates).sum(1, keepdims=True)
expert_out = rng.normal(size=(N, K, Dm)) # 선택된 expert 들의 출력
mix = np.einsum('nk,nkd->nd', gates, expert_out)
print("MoE 결합 == 루프 :", np.allclose(mix, np.stack([sum(gates[n, j] * expert_out[n, j] for j in range(K)) for n in range(N)])))
# Broadcasting 함정
y_true = rng.normal(size=8) # (N,)
y_pred = rng.normal(size=(8, 1)) # (N,1) — 예: Linear(…, 1) 의 출력
bad = ((y_true - y_pred) ** 2).mean() # (N,) - (N,1) → (N,N): 모든 쌍!
good = ((y_true - y_pred[:, 0]) ** 2).mean()
print(f"\nshape 버그 MSE {bad:.3f} vs 올바른 값 {good:.3f} (y_true - y_pred).shape = {(y_true - y_pred).shape}")
adv = rng.normal(size=4) # sequence 마다 advantage 하나 (B,)
logp = rng.normal(size=(4, 16)) # token 별 log-prob (B,T)
try:
_ = adv * logp
except ValueError as e:
print("(B,) * (B,T) →", e)
print("(B,1) * (B,T) →", (adv[:, None] * logp).shape)query의 shape이 (B=4, H=32, T=2048, D=128), key가 (4, 32, 2048, 128)이다. einsum('bhtd,bhsd->bhts', q, k)의 비용은?
다섯 index 의 모든 조합마다 곱셈-덧셈이 한 번이므로 FLOPs . 인자가 attention의 이차 비용이다. 출력만 해도 점수 개, 약 0.5 G 원소(bf16으로 1 GB)라서 FlashAttention은 이것을 메모리에 만들지 않는다.
step d를 어떤 노름으로 잴 때 최급강하 방향이 −sign(g), 즉 이동평균을 끈 Adam의 방향이 되는가?
는 모서리 에서 값 로 달성된다(의 쌍대는 ). 라면 , 이라면 가장 큰 좌표 하나만 움직인다.
정리
- 행렬은 기저 벡터의 상을 열로 갖는 선형 사상이다. 곱은 합성이고, 결합법칙은 성립하지만 교환법칙은 아니며, 괄호 위치가 비용을 바꾼다.
- . 무작위 내적은 로 커지므로 attention에 가 들어간다.
- 노름은 자다. 최급 방향은 자에 따라 다르다. , . 행렬에서는 Frobenius 대 spectral.
- 는 최대 늘임 배율이고 곱에 대해 부등식을 만족하므로, layer들의 곱이 신호를 얼마나 키울 수 있는지 묶어 준다.
- 텐서 식은 einsum으로 읽는다. 합해지는 글자, batch 글자, 비용 . broadcasting은 오른쪽부터, 그리고
(N,)대(N,1)을 조심한다.
이 사이트에서 쓰이는 곳
- Attention — 와 위의 분산 논증. Transformer —
(B,T,C)↔(B,H,T,D). - GPT를 바닥부터 — forward pass의 모든 shape을 직접 써 본다.
- Attention과 KV: MHA → GQA → MLA — broadcasting으로 하는 GQA, einsum으로 쓴 MLA의 absorb(괄호 옮기기).
- MoE 해부 — gate × expert 출력의 결합 einsum. Linear attention과 SSM — 외적의 합으로서의 상태.
- Optimizer와 Muon — 전역 ℓ₂ 노름 gradient clipping, ℓ∞ 최급강하로서의 sign descent, spectral norm 최급강하.
- 안정화 구성요소 — RMSNorm, QK-norm(코사인에 가까운 logit).
- Sequence 대 token 집계 —
(B,1)advantage를 mask와 함께(B,T)token에 broadcast. - 다음: 고유값, SVD, 저랭크.
더 읽을거리Further reading
- Boyd & Vandenberghe, Introduction to Applied Linear Algebra: Vectors, Matrices, and Least Squares (Cambridge, 2018) — 벡터·노름·행렬곱을 응용 중심으로. 무료 PDF.Vectors, norms and matrix products with an applied slant. Free PDF.
- Strang, Introduction to Linear Algebra, 6th ed. (Wellesley-Cambridge, 2023) — 열 관점(column picture)과 네 개의 기본 부분공간The column picture and the four fundamental subspaces
- Goodfellow, Bengio, Courville, Deep Learning, ch. 2 (MIT Press, 2016) — 딥러닝에 필요한 선형대수 요약. 노름·broadcasting 표기The linear algebra deep learning needs, incl. norms and broadcasting notation
- Horn & Johnson, Matrix Analysis, 2nd ed., ch. 5 (Cambridge, 2012) — 벡터·행렬 노름, 쌍대 노름, 노름 사이 부등식의 표준 참고서The standard reference on vector and matrix norms, dual norms and norm inequalities
- NumPy documentation — Broadcasting; numpy.einsum — broadcasting 규칙의 공식 정의The official statement of the broadcasting rules
- 3Blue1Brown, Essence of Linear Algebra (video series, 2016) — "행렬 = 공간의 변환" 직관을 애니메이션으로The "matrix = transformation of space" intuition, animated