A matrix written in standard coordinates hides what it does. Two factorizations choose better coordinates. The eigendecomposition answers “what happens when I apply this square map over and over?” — the question behind gradient-descent dynamics, RNN stability, Hessian curvature and power iteration. The SVD answers “how does this map send inputs to outputs?” for any matrix — the question behind compression (LoRA, MLA), conditioning, least squares and Muon. This lesson derives both, then the four tools built on them: low-rank approximation, orthogonal matrices, the condition number and the pseudo-inverse.
Eigenvectors: directions that stay on their line
A nonzero with is an eigenvector; is its eigenvalue. must be singular, so the eigenvalues are the roots of . For this is :
so and (true in any dimension). If the discriminant is negative the eigenvalues are complex and no real direction stays on its line — the map contains a rotation.
If has independent eigenvectors, stack them in : , so and
Repeated application multiplies each eigen-component by : components with explode, with vanish. This is the whole of the GD stability analysis ( applied times) and of vanishing/exploding RNN gradients. Not every matrix is diagonalizable: a shear has the single eigenvalue 1 and one eigenvector direction.
Power iteration. Write and order . Then
so lines up with at rate per step. It needs only matrix–vector products, which is why it is how one estimates the top Hessian eigenvalue (with Hessian-vector products) or a spectral norm (iterating ).
Symmetric matrices: the spectral theorem
If , then (i) every eigenvalue is real and (ii) eigenvectors of different eigenvalues are orthogonal. For (ii): , so . For (i): for a possibly complex eigenpair, and equals its own conjugate when is real symmetric, so is real. The result (with a little more work for repeated eigenvalues) is the spectral theorem:
The quadratic form then decouples: . Hence is positive semidefinite exactly when all , and the Rayleigh quotient ranges over . Hessians, covariance matrices and are all symmetric, so this is the theorem behind every “curvature along the eigen-directions” argument on the site.
SVD: rotate, scale, rotate
Every factors as
with orthonormal (left singular vectors) and (right singular vectors). Derivation. is symmetric PSD, so by the spectral theorem with . Set and for . These are orthonormal: . And for every is , i.e. . Geometrically: rotates (or reflects) the input so the land on the axes, stretches axis by , rotates the result into the output space. The unit sphere becomes an ellipsoid with semi-axes .
표준 좌표로 쓴 행렬은 자기가 무슨 일을 하는지 숨긴다. 두 가지 분해가 더 좋은 좌표를 골라 준다. 고유분해(eigendecomposition) 는 “이 정사각 사상을 반복해서 적용하면 어떻게 되나?”에 답한다. 경사하강법의 동역학, RNN의 안정성, Hessian 곡률, power iteration 뒤에 있는 질문이다. SVD는 어떤 행렬에 대해서든 “이 사상이 입력을 출력으로 어떻게 보내나?”에 답한다. 압축(LoRA, MLA), 조건수, 최소제곱, Muon 뒤에 있는 질문이다. 이 레슨은 둘을 유도하고, 그 위에 세워진 네 도구, 즉 저랭크 근사, 직교 행렬, 조건수, 유사역행렬을 다룬다.
고유벡터: 자기 직선 위에 머무는 방향
를 만족하는 0 아닌 가 고유벡터(eigenvector) 이고 가 고유값이다. 가 특이해야 하므로 고유값은 의 근이다. 이면 이므로
이고 , 이다(어느 차원에서나 성립). 판별식이 음수면 고유값이 복소수이고, 자기 직선 위에 머무는 실수 방향이 없다. 사상 안에 회전이 들어 있다는 뜻이다.
가 일차독립인 고유벡터 개를 가지면 그것들을 에 쌓아 , 즉 이고
이다. 반복 적용은 각 고유 성분에 를 곱한다. 인 성분은 폭발하고 인 성분은 사라진다. GD 안정성 분석(를 번 적용)과 RNN gradient의 소실·폭발이 전부 이것이다. 모든 행렬이 대각화되지는 않는다. 밀림 은 고유값이 1 하나이고 고유벡터 방향도 하나뿐이다.
Power iteration. 로 쓰고 로 정렬하면
이므로 는 step마다 의 비율로 에 정렬된다. 행렬-벡터 곱만 있으면 되므로, Hessian의 최대 고유값(Hessian-vector product로)이나 spectral norm(를 반복)을 추정하는 표준 방법이다.
대칭 행렬: 스펙트럼 정리
이면 (i) 모든 고유값이 실수이고 (ii) 서로 다른 고유값의 고유벡터는 직교한다. (ii): 이므로 . (i): 복소수일 수도 있는 고유쌍에 대해 이고, 가 실대칭이면 는 자기 켤레와 같으므로 는 실수다. 여기에 중복 고유값을 조금 더 다루면 스펙트럼 정리(spectral theorem) 가 된다.
그러면 이차형식이 분리된다. . 따라서 는 모든 일 때 정확히 양의 준정부호(PSD)이고, Rayleigh quotient 는 를 움직인다. Hessian, 공분산 행렬, 가 모두 대칭이므로, 이 사이트의 “고유 방향별 곡률” 논증은 모두 이 정리 위에 있다.
SVD: 회전, 배율, 회전
모든 은 다음처럼 분해된다.
(왼쪽 특이벡터)와 (오른쪽 특이벡터)는 정규직교다. 유도. 는 대칭 PSD이므로 스펙트럼 정리에 의해 , 이다. , 에 대해 로 두자. 이들은 정규직교다. . 그리고 모든 에 대한 가 , 즉 이다. 기하학적으로는 가 입력을 회전(또는 반사)시켜 를 좌표축에 놓고, 가 번째 축을 배 늘이고, 가 결과를 출력 공간으로 회전시킨다. 단위구는 반축이 인 타원체가 된다.
What to read off the SVD:
- and (orthogonal factors do not change either norm); = number of nonzero ; for square , .
- Eigen vs singular. For symmetric the SVD is the same decomposition with (signs moved into ). For a general square matrix they differ: eigenvectors need not be orthogonal, singular vectors always are, and every (since is bounded by the extreme stretches). A non-normal matrix can have all — so eventually — while makes grow first.
- Orthogonal matrices () are exactly the matrices with all : they preserve lengths and angles, , , and products of them stay orthogonal. RoPE rotates and by orthogonal blocks , and depends only on the offset. DeltaNet’s transition () has eigenvalue along and 1 elsewhere; at it is a Householder reflection.
Low-rank approximation: Eckart–Young
Keep the first terms, . Eckart–Young–Mirsky: for every with ,
Proof (spectral case). has dimension and has dimension ; in they must share a unit vector . Then . The truncated SVD attains it because . So the singular-value spectrum is the compressibility curve.
SVD에서 읽어 낼 것:
- , (직교 인자는 두 노름을 바꾸지 않는다). 는 0 아닌 의 개수, 정사각 이면 .
- 고유 대 특이. 대칭 의 SVD는 같은 분해이고 다(부호는 로 옮긴다). 일반 정사각 행렬에서는 다르다. 고유벡터는 직교할 필요가 없지만 특이벡터는 항상 직교하고, 모든 이다(가 극단적인 늘임 사이에 있으므로). 비정규(non-normal) 행렬은 모든 이어서 결국 이면서도, 때문에 처음에는 가 커질 수 있다.
- 직교 행렬()은 정확히 모든 인 행렬이다. 길이와 각도를 보존하고, , 이며, 직교 행렬끼리의 곱도 직교 행렬이다. RoPE는 와 를 직교 블록 으로 회전시키고, 는 위치 차이에만 의존한다. DeltaNet의 전이 ()는 방향 고유값이 , 나머지는 1이다. 이면 Householder 반사다.
저랭크 근사: Eckart–Young
처음 개 항만 남긴 를 보자. Eckart–Young–Mirsky 정리: 인 모든 에 대해
증명(spectral 경우). 의 차원은 이상이고 의 차원은 이므로, 안에서 둘은 단위벡터 를 공유해야 한다. 그러면 이다. 이므로 절단 SVD가 이 하한을 달성한다. 즉 특이값 스펙트럼이 곧 압축 가능성 곡선이다.
A rank- factorization stores numbers instead of . That trade is behind three methods used later. LoRA freezes and learns with , , betting that the fine-tuning update has a fast-decaying spectrum. MLA caches a -dimensional latent per token (plus a small decoupled RoPE key) and reconstructs keys and values with up-projections, i.e. it constrains the stacked KV projection to rank . PCA keeps the top right singular vectors of centred data, which are the top eigenvectors of its covariance.
The condition number
For invertible , (for SPD matrices, ). It bounds error amplification: if and , then and , so
The same number sets optimisation speed: on a quadratic with Hessian , GD at its best fixed step contracts the error by per step (gradient descent). Orthogonal matrices have , the best possible — one reading of why Muon’s orthogonalised update is well-behaved.
Least squares and the pseudo-inverse
Minimise . The gradient vanishes at the normal equations . With the thin SVD and full column rank,
and the fit is the orthogonal projection of onto the column space. The pseudo-inverse (invert the nonzero , leave zeros) also covers rank-deficient and underdetermined cases, where it returns the minimum-norm solution: any null-space component only adds length. Numerically, never form when is ill-conditioned: , so a condition number becomes , at the edge of float64.
Implementing it
Three blocks: the eigen/SVD identities and power iteration; least squares, the pseudo-inverse and the condition number; and the uses — PCA, Newton–Schulz for , LoRA’s parameter count and a Hessian eigenvalue from Hessian-vector products.
import numpy as np
rng = np.random.default_rng(0)
# --- 1. Spectral theorem and power iteration -------------------------------
Q0, _ = np.linalg.qr(rng.normal(size=(6, 6)))
S = Q0 @ np.diag([5.0, 3.0, 2.0, 1.0, -1.0, 0.5]) @ Q0.T # symmetric, known spectrum
lam, Q = np.linalg.eigh(S) # ascending eigenvalues, orthonormal Q
print("S == Q Λ Qᵀ :", np.allclose(S, Q @ np.diag(lam) @ Q.T), "| QᵀQ == I :", np.allclose(Q.T @ Q, np.eye(6)), "| λ =", np.round(lam, 3))
x = rng.normal(size=6)
prev = None
print("power iteration on S (λ1 = 5, λ2 = 3):")
for it in range(1, 31):
x = S @ x
x /= np.linalg.norm(x)
err = abs(x @ S @ x - 5.0) # Rayleigh-quotient error
if it % 5 == 0:
print(f" iter {it:2d} xᵀSx = {x @ S @ x:.8f} error {err:.1e} error ratio/step {err/prev:.3f} (theory (λ2/λ1)² = {(3/5)**2:.3f})")
prev = err
# --- 2. SVD and how it relates to the eigendecomposition --------------------
A = rng.normal(size=(8, 5))
U, s, Vt = np.linalg.svd(A, full_matrices=False)
print("\nA == U Σ Vᵀ :", np.allclose(A, U @ np.diag(s) @ Vt))
print("σ² == eig(AᵀA) :", np.allclose(np.sort(s**2), np.linalg.eigvalsh(A.T @ A)))
print(f"‖A‖₂ = σ₁ = {s[0]:.4f} ‖A‖_F = {np.linalg.norm(A):.4f} = √Σσ² = {np.sqrt((s**2).sum()):.4f}")
# --- 3. Eckart–Young: truncated SVD is the best rank-k approximation --------
def rank_k(A, k):
U, s, Vt = np.linalg.svd(A, full_matrices=False)
return U[:, :k] * s[:k] @ Vt[:k]
k = 2
err_svd = np.linalg.norm(A - rank_k(A, k))
best_random = min(np.linalg.norm(A - (P := np.linalg.qr(rng.normal(size=(8, k)))[0]) @ P.T @ A) for _ in range(2000))
print(f"\nrank-{k}: truncated SVD error {err_svd:.4f} = √(Σ_(i>k) σᵢ²) {np.sqrt((s[k:]**2).sum()):.4f}")
print(f" best of 2000 random rank-{k} projections: {best_random:.4f} (never below)")
print(f" spectral error ‖A−A_k‖₂ = {np.linalg.norm(A - rank_k(A, k), 2):.4f} = σ_(k+1) = {s[k]:.4f}")
# --- 4. Orthogonal matrices preserve lengths --------------------------------
Qr, _ = np.linalg.qr(rng.normal(size=(5, 5)))
v = rng.normal(size=5)
print(f"\northogonal Q: ‖Qv‖ = {np.linalg.norm(Qr @ v):.6f}, ‖v‖ = {np.linalg.norm(v):.6f}, |det Q| = {abs(np.linalg.det(Qr)):.3f}, κ(Q) = {np.linalg.cond(Qr):.3f}")n, d = 200, 11
t = np.linspace(0, 1, n)
X = np.stack([t**j for j in range(d)], 1) # polynomial features: nearly dependent columns
theta_true = rng.normal(size=d)
y = X @ theta_true # exact data: only rounding error
s = np.linalg.svd(X, compute_uv=False)
print(f"κ(X) = σ_max/σ_min = {s[0]/s[-1]:.2e} κ(XᵀX) = {np.linalg.cond(X.T @ X):.2e} (κ(X)² = {(s[0]/s[-1])**2:.2e})")
U, s_, Vt = np.linalg.svd(X, full_matrices=False)
X_pinv = Vt.T @ np.diag(1 / s_) @ U.T # X⁺ = V Σ⁻¹ Uᵀ
th_pinv = X_pinv @ y
th_lstsq = np.linalg.lstsq(X, y, rcond=None)[0]
th_normal = np.linalg.solve(X.T @ X, X.T @ y) # normal equations: squares κ
for name, th in [("SVD pseudo-inverse", th_pinv), ("lstsq (SVD-based)", th_lstsq), ("normal equations", th_normal)]:
print(f" {name:20s} ‖θ−θ*‖ = {np.linalg.norm(th - theta_true):.2e}")
print("pinv matches np.linalg.pinv:", np.allclose(X_pinv, np.linalg.pinv(X)))
# underdetermined: infinitely many solutions, X⁺y picks the minimum-norm one
Xw = rng.normal(size=(3, 6)); yw = rng.normal(size=3)
th_min = np.linalg.pinv(Xw) @ yw
null = np.linalg.svd(Xw)[2][3:].T # basis of the null space
th_other = th_min + null @ rng.normal(size=3)
print(f"\nunderdetermined: both solve Xθ=y? {np.allclose(Xw @ th_min, yw)}, {np.allclose(Xw @ th_other, yw)}; ‖θ_pinv‖ = {np.linalg.norm(th_min):.3f} < ‖θ_other‖ = {np.linalg.norm(th_other):.3f}")
# GD on least squares: H = XᵀX/n, step limit 2/λ_max, speed set by κ(H)
Xs = X[:, :3]
H = Xs.T @ Xs / n
ev = np.linalg.eigvalsh(H)
kap = ev[-1] / ev[0]
print(f"\nGD on 3 polynomial features: λ_max(H) = {ev[-1]:.3f} → lr limit 2/λ_max = {2/ev[-1]:.3f}; κ(H) = {kap:.0f}")
print(f" best fixed lr shrinks the error by (κ−1)/(κ+1) = {(kap-1)/(kap+1):.5f} per step → ~{np.log(1e-3)/np.log((kap-1)/(kap+1)):.0f} steps per 1000× reduction")# --- PCA = eigenvectors of the covariance = right singular vectors of centred data
Z = rng.normal(size=(500, 3)) * [3.0, 1.0, 0.3]
R, _ = np.linalg.qr(rng.normal(size=(3, 3)))
Xd = Z @ R.T + [1.0, -2.0, 0.5] # rotated, shifted cloud
Xc = Xd - Xd.mean(0)
evals, evecs = np.linalg.eigh(Xc.T @ Xc / (len(Xc) - 1))
_, sv, Vt = np.linalg.svd(Xc, full_matrices=False)
print("PCA: cov eigenvalues", np.round(evals[::-1], 3), "== σ²/(n−1)", np.round(sv**2 / (len(Xc) - 1), 3))
print(" top direction (eig vs SVD, up to a global sign):", np.isclose(abs(evecs[:, -1] @ Vt[0]), 1.0), "| explained variance of PC1:", round(evals[-1] / evals.sum(), 3))
# --- Muon's polar factor UVᵀ by Newton–Schulz (cubic version) ---------------
G = rng.normal(size=(32, 16))
U, s, Vt = np.linalg.svd(G, full_matrices=False)
X = G / np.linalg.norm(G) # Frobenius scaling puts all σ in (0, 1]
for it in range(25):
X = 1.5 * X - 0.5 * X @ X.T @ X # each σ ↦ 1.5σ − 0.5σ³ → 1
print("\nNewton–Schulz → UVᵀ:", np.allclose(X, U @ Vt, atol=1e-6), "| largest/smallest σ of result:", np.round(np.linalg.svd(X, compute_uv=False)[[0, -1]], 6))
# --- LoRA: a rank-r update costs r(m+n) parameters ---------------------------
m, n_, r = 4096, 4096, 16
print(f"\nLoRA on a {m}×{n_} weight, r={r}: {r*(m+n_):,} trainable vs {m*n_:,} full ({100*r*(m+n_)/(m*n_):.2f}%)")
# --- Hessian top eigenvalue by power iteration on Hessian-vector products ----
N, D = 400, 10
Xl = rng.normal(size=(N, D)) * np.linspace(0.2, 3, D) # features with different scales
yl = (Xl @ rng.normal(size=D) + rng.normal(size=N) > 0).astype(float)
w = rng.normal(size=D) * 0.1
def grad(w): # logistic regression, mean NLL
p = 1 / (1 + np.exp(-Xl @ w))
return Xl.T @ (p - yl) / N
def hvp(w, v, eps=1e-5): # H v without forming H
return (grad(w + eps * v) - grad(w - eps * v)) / (2 * eps)
v = rng.normal(size=D)
for _ in range(100):
v = hvp(w, v); v /= np.linalg.norm(v)
lam_hvp = v @ hvp(w, v)
p = 1 / (1 + np.exp(-Xl @ w))
H = (Xl * (p * (1 - p))[:, None]).T @ Xl / N # exact Hessian Xᵀ diag(p(1−p)) X / N
ev = np.linalg.eigvalsh(H)
print(f"\nHessian λ_max: HVP power iteration {lam_hvp:.5f} exact {ev[-1]:.5f} κ(H) = {ev[-1]/ev[0]:.1f} → local GD step limit 2/λ_max = {2/ev[-1]:.3f}")A matrix has singular values 10, 4, 2, 1. What are the spectral-norm and Frobenius-norm errors of the best rank-2 approximation?
Eckart–Young: and . No other rank-2 matrix does better in either norm.
A design matrix X has condition number 1e5. Roughly how many significant digits can you lose by solving the normal equations XᵀXθ = Xᵀy in float64 (about 16 digits)?
, and a backward-stable solve loses about digits, so about 10 of 16. An SVD- or QR-based solver works with directly and, for small residuals, loses about 5. In float32 (about 7 digits) the normal equations would return noise.
Summary
- Eigenvectors stay on their line; means repeated maps are governed by , and power iteration finds the top one at rate .
- Symmetric matrices have real eigenvalues and orthonormal eigenvectors: , .
- Every matrix is rotate–scale–rotate, ; , , orthogonal ⇔ all .
- Truncated SVD is the best rank- approximation in both norms; the spectrum’s tail is the error. LoRA, MLA and PCA are this.
- bounds error amplification and GD speed; normal equations square it, the pseudo-inverse avoids that and gives minimum-norm solutions.
Where this is used
- Gradient descent and optimizers — eigen-directions of the Hessian, , , rotated valleys and preconditioning.
- Muon — polar factor , Newton–Schulz, spectral norm as the layer’s ruler.
- Unsupervised learning — PCA from the SVD.
- Learning as optimisation, linear models, generalisation — normal equations, squared condition number, minimum-norm solutions and double descent at .
- RNNs and training deep nets — products of Jacobians, eigenvalues and singular values of recurrent and layer maps.
- Attention & KV — MLA’s low-rank latent; linear attention & SSMs — transition matrices and their eigenvalues (DeltaNet’s ); GPT from scratch — RoPE as orthogonal rotations.
- Transformer — where LoRA adapters attach; quantisation — GPTQ’s inverse Hessian.
- Next: calculus — gradients, chain rule, Jacobians; later optimisation uses the Hessian’s spectrum for convexity.
rank 분해 는 개 대신 개의 숫자를 저장한다. 이 거래가 뒤에서 쓰이는 세 방법의 바탕이다. LoRA는 를 얼리고 (, )를 학습한다. 미세조정 업데이트의 스펙트럼이 빨리 감쇠한다는 데 거는 것이다. MLA는 token마다 차원 latent(와 작은 decoupled RoPE key)를 캐시하고 up-projection으로 key와 value를 복원한다. 즉 쌓아 놓은 KV projection을 rank 로 제한한다. PCA는 중심화한 데이터의 상위 오른쪽 특이벡터, 즉 공분산의 상위 고유벡터를 남긴다.
조건수
가역 행렬 에 대해 이다(SPD 행렬이면 ). 이것이 오차 증폭을 묶는다. 이고 이면 , 이므로
같은 숫자가 최적화 속도도 정한다. Hessian이 인 이차 함수에서 가장 좋은 고정 step의 GD는 step마다 오차를 배로 줄인다(경사하강법). 직교 행렬은 가능한 최선인 이다. Muon의 직교화된 업데이트가 다루기 좋은 이유를 읽는 한 가지 방법이다.
최소제곱과 유사역행렬
를 최소화하자. gradient 가 0이 되는 곳이 정규방정식(normal equations) 다. thin SVD , 열 rank가 꽉 찼다면
이고, 적합값 는 를 열공간에 직교 사영한 것이다. 유사역행렬(pseudo-inverse) (0 아닌 만 뒤집고 0은 그대로)는 rank가 부족하거나 미지수가 더 많은 경우도 다루며, 그때는 최소 노름 해를 준다. 영공간 성분은 길이만 늘리기 때문이다. 수치적으로는 의 조건이 나쁠 때 를 절대 만들지 말자. 이라서 조건수 이 가 되고, 이는 float64의 한계에 닿는다.
직접 구현하기
블록 셋. 고유분해·SVD 항등식과 power iteration, 최소제곱·유사역행렬·조건수, 그리고 쓰임새: PCA, 를 위한 Newton–Schulz, LoRA의 매개변수 수, Hessian-vector product로 구하는 Hessian 고유값.
import numpy as np
rng = np.random.default_rng(0)
# --- 1. 스펙트럼 정리와 power iteration ------------------------------------
Q0, _ = np.linalg.qr(rng.normal(size=(6, 6)))
S = Q0 @ np.diag([5.0, 3.0, 2.0, 1.0, -1.0, 0.5]) @ Q0.T # 스펙트럼을 아는 대칭 행렬
lam, Q = np.linalg.eigh(S) # 오름차순 고유값, 정규직교 Q
print("S == Q Λ Qᵀ :", np.allclose(S, Q @ np.diag(lam) @ Q.T), "| QᵀQ == I :", np.allclose(Q.T @ Q, np.eye(6)), "| λ =", np.round(lam, 3))
x = rng.normal(size=6)
prev = None
print("S 에 power iteration (λ1 = 5, λ2 = 3):")
for it in range(1, 31):
x = S @ x
x /= np.linalg.norm(x)
err = abs(x @ S @ x - 5.0) # Rayleigh quotient 오차
if it % 5 == 0:
print(f" iter {it:2d} xᵀSx = {x @ S @ x:.8f} 오차 {err:.1e} step당 오차 비 {err/prev:.3f} (이론 (λ2/λ1)² = {(3/5)**2:.3f})")
prev = err
# --- 2. SVD 와 고유분해의 관계 ----------------------------------------------
A = rng.normal(size=(8, 5))
U, s, Vt = np.linalg.svd(A, full_matrices=False)
print("\nA == U Σ Vᵀ :", np.allclose(A, U @ np.diag(s) @ Vt))
print("σ² == eig(AᵀA) :", np.allclose(np.sort(s**2), np.linalg.eigvalsh(A.T @ A)))
print(f"‖A‖₂ = σ₁ = {s[0]:.4f} ‖A‖_F = {np.linalg.norm(A):.4f} = √Σσ² = {np.sqrt((s**2).sum()):.4f}")
# --- 3. Eckart–Young: 절단 SVD 가 최선의 rank-k 근사 ------------------------
def rank_k(A, k):
U, s, Vt = np.linalg.svd(A, full_matrices=False)
return U[:, :k] * s[:k] @ Vt[:k]
k = 2
err_svd = np.linalg.norm(A - rank_k(A, k))
best_random = min(np.linalg.norm(A - (P := np.linalg.qr(rng.normal(size=(8, k)))[0]) @ P.T @ A) for _ in range(2000))
print(f"\nrank-{k}: 절단 SVD 오차 {err_svd:.4f} = √(Σ_(i>k) σᵢ²) {np.sqrt((s[k:]**2).sum()):.4f}")
print(f" 무작위 rank-{k} 사영 2000개 중 최선: {best_random:.4f} (절대 더 작지 않다)")
print(f" spectral 오차 ‖A−A_k‖₂ = {np.linalg.norm(A - rank_k(A, k), 2):.4f} = σ_(k+1) = {s[k]:.4f}")
# --- 4. 직교 행렬은 길이를 보존한다 ------------------------------------------
Qr, _ = np.linalg.qr(rng.normal(size=(5, 5)))
v = rng.normal(size=5)
print(f"\n직교 Q: ‖Qv‖ = {np.linalg.norm(Qr @ v):.6f}, ‖v‖ = {np.linalg.norm(v):.6f}, |det Q| = {abs(np.linalg.det(Qr)):.3f}, κ(Q) = {np.linalg.cond(Qr):.3f}")n, d = 200, 11
t = np.linspace(0, 1, n)
X = np.stack([t**j for j in range(d)], 1) # 다항식 특징: 거의 종속인 열
theta_true = rng.normal(size=d)
y = X @ theta_true # 정확한 데이터: 반올림 오차만
s = np.linalg.svd(X, compute_uv=False)
print(f"κ(X) = σ_max/σ_min = {s[0]/s[-1]:.2e} κ(XᵀX) = {np.linalg.cond(X.T @ X):.2e} (κ(X)² = {(s[0]/s[-1])**2:.2e})")
U, s_, Vt = np.linalg.svd(X, full_matrices=False)
X_pinv = Vt.T @ np.diag(1 / s_) @ U.T # X⁺ = V Σ⁻¹ Uᵀ
th_pinv = X_pinv @ y
th_lstsq = np.linalg.lstsq(X, y, rcond=None)[0]
th_normal = np.linalg.solve(X.T @ X, X.T @ y) # 정규방정식: κ 를 제곱한다
for name, th in [("SVD 유사역행렬", th_pinv), ("lstsq (SVD 기반)", th_lstsq), ("정규방정식", th_normal)]:
print(f" {name:20s} ‖θ−θ*‖ = {np.linalg.norm(th - theta_true):.2e}")
print("np.linalg.pinv 와 일치:", np.allclose(X_pinv, np.linalg.pinv(X)))
# 미지수가 더 많을 때: 해가 무한히 많고, X⁺y 는 최소 노름 해를 고른다
Xw = rng.normal(size=(3, 6)); yw = rng.normal(size=3)
th_min = np.linalg.pinv(Xw) @ yw
null = np.linalg.svd(Xw)[2][3:].T # 영공간의 기저
th_other = th_min + null @ rng.normal(size=3)
print(f"\n부족결정: 둘 다 Xθ=y 를 푸나? {np.allclose(Xw @ th_min, yw)}, {np.allclose(Xw @ th_other, yw)}; ‖θ_pinv‖ = {np.linalg.norm(th_min):.3f} < ‖θ_other‖ = {np.linalg.norm(th_other):.3f}")
# 최소제곱의 GD: H = XᵀX/n, step 상한 2/λ_max, 속도는 κ(H)
Xs = X[:, :3]
H = Xs.T @ Xs / n
ev = np.linalg.eigvalsh(H)
kap = ev[-1] / ev[0]
print(f"\n다항식 특징 3개의 GD: λ_max(H) = {ev[-1]:.3f} → lr 상한 2/λ_max = {2/ev[-1]:.3f}; κ(H) = {kap:.0f}")
print(f" 최선의 고정 lr 은 step 마다 오차를 (κ−1)/(κ+1) = {(kap-1)/(kap+1):.5f} 배로 → 1000배 줄이는 데 ~{np.log(1e-3)/np.log((kap-1)/(kap+1)):.0f} step")# --- PCA = 공분산의 고유벡터 = 중심화한 데이터의 오른쪽 특이벡터
Z = rng.normal(size=(500, 3)) * [3.0, 1.0, 0.3]
R, _ = np.linalg.qr(rng.normal(size=(3, 3)))
Xd = Z @ R.T + [1.0, -2.0, 0.5] # 회전·이동한 점 구름
Xc = Xd - Xd.mean(0)
evals, evecs = np.linalg.eigh(Xc.T @ Xc / (len(Xc) - 1))
_, sv, Vt = np.linalg.svd(Xc, full_matrices=False)
print("PCA: 공분산 고유값", np.round(evals[::-1], 3), "== σ²/(n−1)", np.round(sv**2 / (len(Xc) - 1), 3))
print(" 최상위 방향 (eig vs SVD, 전역 부호 제외):", np.isclose(abs(evecs[:, -1] @ Vt[0]), 1.0), "| PC1 설명 분산 비율:", round(evals[-1] / evals.sum(), 3))
# --- Muon 의 polar factor UVᵀ 를 Newton–Schulz 로 (3차 버전) ------------------
G = rng.normal(size=(32, 16))
U, s, Vt = np.linalg.svd(G, full_matrices=False)
X = G / np.linalg.norm(G) # Frobenius 로 나누면 모든 σ 가 (0, 1]
for it in range(25):
X = 1.5 * X - 0.5 * X @ X.T @ X # 각 σ ↦ 1.5σ − 0.5σ³ → 1
print("\nNewton–Schulz → UVᵀ:", np.allclose(X, U @ Vt, atol=1e-6), "| 결과의 최대/최소 σ:", np.round(np.linalg.svd(X, compute_uv=False)[[0, -1]], 6))
# --- LoRA: rank-r 업데이트의 매개변수는 r(m+n) 개 ------------------------------
m, n_, r = 4096, 4096, 16
print(f"\n{m}×{n_} weight 에 LoRA, r={r}: 학습 {r*(m+n_):,} 개 vs 전체 {m*n_:,} 개 ({100*r*(m+n_)/(m*n_):.2f}%)")
# --- Hessian-vector product 에 power iteration 으로 Hessian 최대 고유값 --------
N, D = 400, 10
Xl = rng.normal(size=(N, D)) * np.linspace(0.2, 3, D) # 스케일이 다른 특징
yl = (Xl @ rng.normal(size=D) + rng.normal(size=N) > 0).astype(float)
w = rng.normal(size=D) * 0.1
def grad(w): # 로지스틱 회귀, 평균 NLL
p = 1 / (1 + np.exp(-Xl @ w))
return Xl.T @ (p - yl) / N
def hvp(w, v, eps=1e-5): # H 를 만들지 않고 H v
return (grad(w + eps * v) - grad(w - eps * v)) / (2 * eps)
v = rng.normal(size=D)
for _ in range(100):
v = hvp(w, v); v /= np.linalg.norm(v)
lam_hvp = v @ hvp(w, v)
p = 1 / (1 + np.exp(-Xl @ w))
H = (Xl * (p * (1 - p))[:, None]).T @ Xl / N # 정확한 Hessian Xᵀ diag(p(1−p)) X / N
ev = np.linalg.eigvalsh(H)
print(f"\nHessian λ_max: HVP power iteration {lam_hvp:.5f} 정확한 값 {ev[-1]:.5f} κ(H) = {ev[-1]/ev[0]:.1f} → 국소 GD step 상한 2/λ_max = {2/ev[-1]:.3f}")특이값이 10, 4, 2, 1인 행렬이 있다. 최선의 rank 2 근사의 spectral 노름 오차와 Frobenius 노름 오차는?
Eckart–Young: , . 어떤 다른 rank 2 행렬도 두 노름 모두에서 이보다 나을 수 없다.
설계 행렬 X의 조건수가 1e5다. float64(유효숫자 약 16자리)에서 정규방정식 XᵀXθ = Xᵀy를 풀면 유효숫자를 대략 몇 자리 잃을 수 있나?
이고, backward-stable한 풀이는 대략 자리를 잃으므로 16자리 중 약 10자리다. SVD나 QR 기반 풀이는 를 직접 다루므로 잔차가 작으면 약 5자리만 잃는다. float32(약 7자리)라면 정규방정식은 잡음을 돌려준다.
정리
- 고유벡터는 자기 직선 위에 머문다. 이므로 반복 사상은 가 지배하고, power iteration은 의 속도로 최상위 고유벡터를 찾는다.
- 대칭 행렬은 실수 고유값과 정규직교 고유벡터를 갖는다. , .
- 모든 행렬은 회전-배율-회전 이다. , , 직교 ⇔ 모든 .
- 절단 SVD는 두 노름 모두에서 최선의 rank 근사이고, 스펙트럼의 꼬리가 곧 오차다. LoRA, MLA, PCA가 이것이다.
- 은 오차 증폭과 GD 속도를 묶는다. 정규방정식은 이를 제곱하고, 유사역행렬 는 그것을 피하며 최소 노름 해를 준다.
이 사이트에서 쓰이는 곳
- 경사하강법과 optimizer — Hessian의 고유 방향, , , 회전된 골짜기와 preconditioning.
- Muon — polar factor , Newton–Schulz, layer의 자로서의 spectral norm.
- 비지도 학습 — SVD로 하는 PCA.
- 최적화로서의 학습, 선형 모델, 일반화 — 정규방정식, 제곱되는 조건수, 최소 노름 해, 에서의 double descent.
- RNN과 깊은 망 학습 — Jacobian의 곱, 순환·layer 사상의 고유값과 특이값.
- Attention과 KV — MLA의 저랭크 latent. Linear attention과 SSM — 전이 행렬과 그 고유값(DeltaNet의 ). GPT를 바닥부터 — 직교 회전으로서의 RoPE.
- Transformer — LoRA adapter를 붙이는 곳. 양자화 — GPTQ의 역 Hessian.
- 다음: 미분 — gradient, 연쇄법칙, Jacobian. 이어지는 최적화는 Hessian의 스펙트럼으로 볼록성을 다룬다.
더 읽을거리Further reading
- Trefethen & Bau, Numerical Linear Algebra (SIAM, 1997), Lectures 4–5, 11–12, 27 — SVD의 기하, 최소제곱, 조건수, power iteration을 가장 깔끔하게The cleanest treatment of SVD geometry, least squares, conditioning and power iteration
- Strang, Linear Algebra and Learning from Data (Wellesley-Cambridge, 2019) — 저랭크 근사·PCA·딥러닝을 한 책에서Low-rank approximation, PCA and deep learning in one book
- Eckart & Young, The approximation of one matrix by another of lower rank (Psychometrika 1(3), 1936) — 절단 SVD가 최적 저랭크 근사라는 원 논문The original result that truncated SVD is the optimal low-rank approximation
- Golub & Van Loan, Matrix Computations, 4th ed. (Johns Hopkins, 2013) — 고유값·SVD 알고리즘(Jacobi, QR, power)과 섭동 이론의 표준서The standard reference for eigen/SVD algorithms (Jacobi, QR, power) and perturbation theory
- Hu et al., LoRA: Low-Rank Adaptation of Large Language Models (ICLR 2022) — 미세조정 업데이트를 rank r 행렬 BA로 제한Restricting the fine-tuning update to a rank-r product BA
- Jordan et al., Muon: An optimizer for hidden layers in neural networks (blog, 2024) — 모멘텀의 polar factor UVᵀ를 Newton–Schulz로 계산Computing the momentum's polar factor UVᵀ with Newton–Schulz