Track 0 · Math Foundations · 02/10

고유값·SVD·저랭크Eigenvalues, SVD and low rank

고유분해와 SVD로 행렬을 "가장 좋은 좌표"에서 읽는다. power iteration, 스펙트럼 정리, 회전-배율-회전, Eckart–Young 저랭크 근사, 직교 행렬, 조건수, 유사역행렬을 유도하고 PCA·Muon·LoRA·MLA·Hessian으로 잇는다.Read a matrix in its best coordinates with the eigendecomposition and the SVD. Derive power iteration, the spectral theorem, rotate–scale–rotate, Eckart–Young low-rank approximation, orthogonal matrices, the condition number and the pseudo-inverse, and connect them to PCA, Muon, LoRA, MLA and Hessians.

45 분min linear algebra · eigenvalues · SVD · low rank · condition number · least squares · PCA 먼저 볼 것:Before this: 벡터·행렬·텐서Vectors, matrices and tensors

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 vv with Av=λvAv = \lambda v is an eigenvector; λ\lambda is its eigenvalue. A−λIA - \lambda I must be singular, so the eigenvalues are the roots of det⁡(A−λI)=0\det(A - \lambda I) = 0. For 2×22\times 2 this is λ2−(tr⁡A)λ+det⁡A=0\lambda^2 - (\operatorname{tr}A)\lambda + \det A = 0:

λ1,2=12tr⁡A±14(tr⁡A)2−det⁡A,\lambda_{1,2} = \tfrac12\operatorname{tr}A \pm \sqrt{\tfrac14(\operatorname{tr}A)^2 - \det A},

so λ1+λ2=tr⁡A\lambda_1+\lambda_2 = \operatorname{tr}A and λ1λ2=det⁡A\lambda_1\lambda_2 = \det A (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 AA has nn independent eigenvectors, stack them in PP: AP=PΛAP = P\Lambda, so A=PΛP−1A = P\Lambda P^{-1} and

Ak=PΛkP−1.A^k = P\Lambda^k P^{-1}.

Repeated application multiplies each eigen-component by λik\lambda_i^k: components with ∣λi∣>1|\lambda_i| > 1 explode, with ∣λi∣<1|\lambda_i| < 1 vanish. This is the whole of the GD stability analysis (I−ηHI - \eta H applied kk times) and of vanishing/exploding RNN gradients. Not every matrix is diagonalizable: a shear (1101)\left(\begin{smallmatrix}1&1\\0&1\end{smallmatrix}\right) has the single eigenvalue 1 and one eigenvector direction.

Power iteration. Write x0=∑icivix_0 = \sum_i c_i v_i and order ∣λ1∣>∣λ2∣≥…|\lambda_1| > |\lambda_2| \ge \dots. Then

Akx0=λ1k(c1v1+∑i≥2ci(λi/λ1)kvi),A^k x_0 = \lambda_1^k\Big(c_1 v_1 + \sum_{i\ge2} c_i (\lambda_i/\lambda_1)^k v_i\Big),

so xk=Akx0/∥Akx0∥x_k = A^k x_0/\|A^k x_0\| lines up with v1v_1 at rate ∣λ2/λ1∣|\lambda_2/\lambda_1| 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 A⊤AA^\top A).

Symmetric matrices: the spectral theorem

If S=S⊤S = S^\top, then (i) every eigenvalue is real and (ii) eigenvectors of different eigenvalues are orthogonal. For (ii): λ1v1⊤v2=(Sv1)⊤v2=v1⊤Sv2=λ2v1⊤v2\lambda_1 v_1^\top v_2 = (Sv_1)^\top v_2 = v_1^\top S v_2 = \lambda_2 v_1^\top v_2, so (λ1−λ2)v1⊤v2=0(\lambda_1 - \lambda_2)v_1^\top v_2 = 0. For (i): for a possibly complex eigenpair, vˉ⊤Sv=λ∥v∥2\bar v^\top S v = \lambda\|v\|^2 and vˉ⊤Sv\bar v^\top S v equals its own conjugate when SS is real symmetric, so λ\lambda is real. The result (with a little more work for repeated eigenvalues) is the spectral theorem:

S=QΛQ⊤=∑iλi qiqi⊤,Q⊤Q=I.S = Q\Lambda Q^\top = \sum_i \lambda_i\, q_i q_i^\top, \qquad Q^\top Q = I.

The quadratic form then decouples: x⊤Sx=∑iλi(qi⊤x)2x^\top S x = \sum_i \lambda_i (q_i^\top x)^2. Hence SS is positive semidefinite exactly when all λi≥0\lambda_i \ge 0, and the Rayleigh quotient x⊤Sx/x⊤xx^\top Sx/x^\top x ranges over [λmin⁡,λmax⁡][\lambda_{\min}, \lambda_{\max}]. Hessians, covariance matrices and A⊤AA^\top A are all symmetric, so this is the theorem behind every “curvature along the eigen-directions” argument on the site.

SVD: rotate, scale, rotate

Every A∈Rm×nA\in\mathbb R^{m\times n} factors as

A=UΣV⊤=∑i=1rσi uivi⊤,σ1≥⋯≥σr>0,A = U\Sigma V^\top = \sum_{i=1}^{r} \sigma_i\, u_i v_i^\top, \qquad \sigma_1 \ge \dots \ge \sigma_r > 0,

with orthonormal uiu_i (left singular vectors) and viv_i (right singular vectors). Derivation. A⊤AA^\top A is symmetric PSD, so by the spectral theorem A⊤A=VΛV⊤A^\top A = V\Lambda V^\top with λi≥0\lambda_i \ge 0. Set σi=λi\sigma_i = \sqrt{\lambda_i} and ui=Avi/σiu_i = Av_i/\sigma_i for σi>0\sigma_i > 0. These are orthonormal: ui⊤uj=vi⊤A⊤Avj/(σiσj)=λj δij/(σiσj)=δiju_i^\top u_j = v_i^\top A^\top A v_j/(\sigma_i\sigma_j) = \lambda_j\,\delta_{ij}/(\sigma_i\sigma_j) = \delta_{ij}. And Avi=σiuiAv_i = \sigma_i u_i for every ii is AV=UΣAV = U\Sigma, i.e. A=UΣV⊤A = U\Sigma V^\top. Geometrically: V⊤V^\top rotates (or reflects) the input so the viv_i land on the axes, Σ\Sigma stretches axis ii by σi\sigma_i, UU rotates the result into the output space. The unit sphere becomes an ellipsoid with semi-axes σiui\sigma_i u_i.

표준 좌표로 쓴 행렬은 자기가 무슨 일을 하는지 숨긴다. 두 가지 분해가 더 좋은 좌표를 골라 준다. 고유분해(eigendecomposition) 는 “이 정사각 사상을 반복해서 적용하면 어떻게 되나?”에 답한다. 경사하강법의 동역학, RNN의 안정성, Hessian 곡률, power iteration 뒤에 있는 질문이다. SVD는 어떤 행렬에 대해서든 “이 사상이 입력을 출력으로 어떻게 보내나?”에 답한다. 압축(LoRA, MLA), 조건수, 최소제곱, Muon 뒤에 있는 질문이다. 이 레슨은 둘을 유도하고, 그 위에 세워진 네 도구, 즉 저랭크 근사, 직교 행렬, 조건수, 유사역행렬을 다룬다.

고유벡터: 자기 직선 위에 머무는 방향

Av=λvAv = \lambda v를 만족하는 0 아닌 vv가 고유벡터(eigenvector) 이고 λ\lambda가 고유값이다. A−λIA - \lambda I가 특이해야 하므로 고유값은 det⁡(A−λI)=0\det(A - \lambda I) = 0의 근이다. 2×22\times 2이면 λ2−(tr⁡A)λ+det⁡A=0\lambda^2 - (\operatorname{tr}A)\lambda + \det A = 0이므로

λ1,2=12tr⁡A±14(tr⁡A)2−det⁡A\lambda_{1,2} = \tfrac12\operatorname{tr}A \pm \sqrt{\tfrac14(\operatorname{tr}A)^2 - \det A}

이고 λ1+λ2=tr⁡A\lambda_1+\lambda_2 = \operatorname{tr}A, λ1λ2=det⁡A\lambda_1\lambda_2 = \det A이다(어느 차원에서나 성립). 판별식이 음수면 고유값이 복소수이고, 자기 직선 위에 머무는 실수 방향이 없다. 사상 안에 회전이 들어 있다는 뜻이다.

AA가 일차독립인 고유벡터 nn개를 가지면 그것들을 PP에 쌓아 AP=PΛAP = P\Lambda, 즉 A=PΛP−1A = P\Lambda P^{-1}이고

Ak=PΛkP−1A^k = P\Lambda^k P^{-1}

이다. 반복 적용은 각 고유 성분에 λik\lambda_i^k를 곱한다. ∣λi∣>1|\lambda_i| > 1인 성분은 폭발하고 ∣λi∣<1|\lambda_i| < 1인 성분은 사라진다. GD 안정성 분석(I−ηHI - \eta H를 kk번 적용)과 RNN gradient의 소실·폭발이 전부 이것이다. 모든 행렬이 대각화되지는 않는다. 밀림 (1101)\left(\begin{smallmatrix}1&1\\0&1\end{smallmatrix}\right)은 고유값이 1 하나이고 고유벡터 방향도 하나뿐이다.

Power iteration. x0=∑icivix_0 = \sum_i c_i v_i로 쓰고 ∣λ1∣>∣λ2∣≥…|\lambda_1| > |\lambda_2| \ge \dots로 정렬하면

Akx0=λ1k(c1v1+∑i≥2ci(λi/λ1)kvi)A^k x_0 = \lambda_1^k\Big(c_1 v_1 + \sum_{i\ge2} c_i (\lambda_i/\lambda_1)^k v_i\Big)

이므로 xk=Akx0/∥Akx0∥x_k = A^k x_0/\|A^k x_0\|는 step마다 ∣λ2/λ1∣|\lambda_2/\lambda_1|의 비율로 v1v_1에 정렬된다. 행렬-벡터 곱만 있으면 되므로, Hessian의 최대 고유값(Hessian-vector product로)이나 spectral norm(A⊤AA^\top A를 반복)을 추정하는 표준 방법이다.

대칭 행렬: 스펙트럼 정리

S=S⊤S = S^\top이면 (i) 모든 고유값이 실수이고 (ii) 서로 다른 고유값의 고유벡터는 직교한다. (ii): λ1v1⊤v2=(Sv1)⊤v2=v1⊤Sv2=λ2v1⊤v2\lambda_1 v_1^\top v_2 = (Sv_1)^\top v_2 = v_1^\top S v_2 = \lambda_2 v_1^\top v_2이므로 (λ1−λ2)v1⊤v2=0(\lambda_1 - \lambda_2)v_1^\top v_2 = 0. (i): 복소수일 수도 있는 고유쌍에 대해 vˉ⊤Sv=λ∥v∥2\bar v^\top S v = \lambda\|v\|^2이고, SS가 실대칭이면 vˉ⊤Sv\bar v^\top S v는 자기 켤레와 같으므로 λ\lambda는 실수다. 여기에 중복 고유값을 조금 더 다루면 스펙트럼 정리(spectral theorem) 가 된다.

S=QΛQ⊤=∑iλi qiqi⊤,Q⊤Q=I.S = Q\Lambda Q^\top = \sum_i \lambda_i\, q_i q_i^\top, \qquad Q^\top Q = I.

그러면 이차형식이 분리된다. x⊤Sx=∑iλi(qi⊤x)2x^\top S x = \sum_i \lambda_i (q_i^\top x)^2. 따라서 SS는 모든 λi≥0\lambda_i \ge 0일 때 정확히 양의 준정부호(PSD)이고, Rayleigh quotient x⊤Sx/x⊤xx^\top Sx/x^\top x는 [λmin⁡,λmax⁡][\lambda_{\min}, \lambda_{\max}]를 움직인다. Hessian, 공분산 행렬, A⊤AA^\top A가 모두 대칭이므로, 이 사이트의 “고유 방향별 곡률” 논증은 모두 이 정리 위에 있다.

SVD: 회전, 배율, 회전

모든 A∈Rm×nA\in\mathbb R^{m\times n}은 다음처럼 분해된다.

A=UΣV⊤=∑i=1rσi uivi⊤,σ1≥⋯≥σr>0,A = U\Sigma V^\top = \sum_{i=1}^{r} \sigma_i\, u_i v_i^\top, \qquad \sigma_1 \ge \dots \ge \sigma_r > 0,

uiu_i(왼쪽 특이벡터)와 viv_i(오른쪽 특이벡터)는 정규직교다. 유도. A⊤AA^\top A는 대칭 PSD이므로 스펙트럼 정리에 의해 A⊤A=VΛV⊤A^\top A = V\Lambda V^\top, λi≥0\lambda_i \ge 0이다. σi=λi\sigma_i = \sqrt{\lambda_i}, σi>0\sigma_i > 0에 대해 ui=Avi/σiu_i = Av_i/\sigma_i로 두자. 이들은 정규직교다. ui⊤uj=vi⊤A⊤Avj/(σiσj)=λj δij/(σiσj)=δiju_i^\top u_j = v_i^\top A^\top A v_j/(\sigma_i\sigma_j) = \lambda_j\,\delta_{ij}/(\sigma_i\sigma_j) = \delta_{ij}. 그리고 모든 ii에 대한 Avi=σiuiAv_i = \sigma_i u_i가 AV=UΣAV = U\Sigma, 즉 A=UΣV⊤A = U\Sigma V^\top이다. 기하학적으로는 V⊤V^\top가 입력을 회전(또는 반사)시켜 viv_i를 좌표축에 놓고, Σ\Sigma가 ii번째 축을 σi\sigma_i배 늘이고, UU가 결과를 출력 공간으로 회전시킨다. 단위구는 반축이 σiui\sigma_i u_i인 타원체가 된다.

Press ▶ or drag the stage slider: Vᵀ rotates the right singular vectors v₁, v₂ (amber, teal) onto the axes, Σ stretches the axes by σ₁ and σ₂, and U rotates the result onto u₁, u₂. Any 2×2 matrix is these three moves. Drag the red/green column tips to change A. The violet dashed lines are the eigenvectors — directions A maps onto themselves; they coincide with the singular vectors only when A is symmetric. Power iteration repeatedly applies A and renormalises: the dots converge to the dominant eigenvector at rate |λ₂/λ₁|, and never settle when the eigenvalues are complex. ▶를 누르거나 단계 슬라이더를 끌어 보세요. Vᵀ가 오른쪽 특이벡터 v₁, v₂(주황, 청록)를 좌표축으로 돌리고, Σ가 축을 σ₁, σ₂배로 늘이고, U가 결과를 u₁, u₂ 방향으로 돌린다. 모든 2×2 행렬은 이 세 동작이다. 빨강·초록 열 끝점을 끌어 A를 바꿀 수 있다. 보라 점선은 고유벡터, 즉 A가 자기 자신의 직선 위로 보내는 방향이다. A가 대칭일 때만 특이벡터와 일치한다. Power iteration은 A를 곱하고 정규화하기를 반복한다. 점들이 |λ₂/λ₁|의 속도로 주 고유벡터에 수렴하고, 고유값이 복소수면 끝없이 돈다.

What to read off the SVD:

  • ∥A∥2=σ1\|A\|_2 = \sigma_1 and ∥A∥F2=∑iσi2\|A\|_F^2 = \sum_i\sigma_i^2 (orthogonal factors do not change either norm); rank⁡A\operatorname{rank}A = number of nonzero σi\sigma_i; for square AA, ∣det⁡A∣=∏iσi|\det A| = \prod_i\sigma_i.
  • Eigen vs singular. For symmetric S=QΛQ⊤S = Q\Lambda Q^\top the SVD is the same decomposition with σi=∣λi∣\sigma_i = |\lambda_i| (signs moved into UU). For a general square matrix they differ: eigenvectors need not be orthogonal, singular vectors always are, and every ∣λi∣∈[σmin⁡,σmax⁡]|\lambda_i| \in [\sigma_{\min}, \sigma_{\max}] (since ∥Av∥=∣λ∣∥v∥\|Av\| = |\lambda|\|v\| is bounded by the extreme stretches). A non-normal matrix can have all ∣λ∣<1|\lambda| < 1 — so Ak→0A^k \to 0 eventually — while σ1>1\sigma_1 > 1 makes ∥Akx∥\|A^k x\| grow first.
  • Orthogonal matrices (Q⊤Q=IQ^\top Q = I) are exactly the matrices with all σi=1\sigma_i = 1: they preserve lengths and angles, det⁡Q=±1\det Q = \pm1, Q−1=Q⊤Q^{-1} = Q^\top, and products of them stay orthogonal. RoPE rotates qq and kk by orthogonal blocks RmR_m, and (Rmq)⊤(Rnk)=q⊤Rn−mk(R_m q)^\top(R_n k) = q^\top R_{n-m}k depends only on the offset. DeltaNet’s transition I−βkk⊤I - \beta kk^\top (∥k∥=1\|k\|=1) has eigenvalue 1−β1-\beta along kk and 1 elsewhere; at β=2\beta = 2 it is a Householder reflection.

Low-rank approximation: Eckart–Young

Keep the first kk terms, Ak=∑i≤kσiuivi⊤A_k = \sum_{i\le k}\sigma_i u_i v_i^\top. Eckart–Young–Mirsky: for every BB with rank⁡B≤k\operatorname{rank}B \le k,

∥A−B∥2≥σk+1=∥A−Ak∥2,∥A−B∥F≥(∑i>kσi2)1/2=∥A−Ak∥F.\|A - B\|_2 \ge \sigma_{k+1} = \|A - A_k\|_2, \qquad \|A - B\|_F \ge \Big(\sum_{i>k}\sigma_i^2\Big)^{1/2} = \|A - A_k\|_F .

Proof (spectral case). null⁡(B)\operatorname{null}(B) has dimension ≥n−k\ge n-k and span⁡(v1,…,vk+1)\operatorname{span}(v_1,\dots,v_{k+1}) has dimension k+1k+1; in Rn\mathbb R^n they must share a unit vector ww. Then ∥(A−B)w∥=∥Aw∥=(∑i≤k+1σi2(vi⊤w)2)1/2≥σk+1\|(A-B)w\| = \|Aw\| = \big(\sum_{i\le k+1}\sigma_i^2 (v_i^\top w)^2\big)^{1/2} \ge \sigma_{k+1}. The truncated SVD attains it because A−Ak=∑i>kσiuivi⊤A - A_k = \sum_{i>k}\sigma_i u_iv_i^\top. So the singular-value spectrum is the compressibility curve.

SVD에서 읽어 낼 것:

  • ∥A∥2=σ1\|A\|_2 = \sigma_1, ∥A∥F2=∑iσi2\|A\|_F^2 = \sum_i\sigma_i^2(직교 인자는 두 노름을 바꾸지 않는다). rank⁡A\operatorname{rank}A는 0 아닌 σi\sigma_i의 개수, 정사각 AA이면 ∣det⁡A∣=∏iσi|\det A| = \prod_i\sigma_i.
  • 고유 대 특이. 대칭 S=QΛQ⊤S = Q\Lambda Q^\top의 SVD는 같은 분해이고 σi=∣λi∣\sigma_i = |\lambda_i|다(부호는 UU로 옮긴다). 일반 정사각 행렬에서는 다르다. 고유벡터는 직교할 필요가 없지만 특이벡터는 항상 직교하고, 모든 ∣λi∣∈[σmin⁡,σmax⁡]|\lambda_i| \in [\sigma_{\min}, \sigma_{\max}]이다(∥Av∥=∣λ∣∥v∥\|Av\| = |\lambda|\|v\|가 극단적인 늘임 사이에 있으므로). 비정규(non-normal) 행렬은 모든 ∣λ∣<1|\lambda| < 1이어서 결국 Ak→0A^k \to 0이면서도, σ1>1\sigma_1 > 1 때문에 처음에는 ∥Akx∥\|A^k x\|가 커질 수 있다.
  • 직교 행렬(Q⊤Q=IQ^\top Q = I)은 정확히 모든 σi=1\sigma_i = 1인 행렬이다. 길이와 각도를 보존하고, det⁡Q=±1\det Q = \pm1, Q−1=Q⊤Q^{-1} = Q^\top이며, 직교 행렬끼리의 곱도 직교 행렬이다. RoPE는 qq와 kk를 직교 블록 RmR_m으로 회전시키고, (Rmq)⊤(Rnk)=q⊤Rn−mk(R_m q)^\top(R_n k) = q^\top R_{n-m}k는 위치 차이에만 의존한다. DeltaNet의 전이 I−βkk⊤I - \beta kk^\top(∥k∥=1\|k\|=1)는 kk 방향 고유값이 1−β1-\beta, 나머지는 1이다. β=2\beta = 2이면 Householder 반사다.

저랭크 근사: Eckart–Young

처음 kk개 항만 남긴 Ak=∑i≤kσiuivi⊤A_k = \sum_{i\le k}\sigma_i u_i v_i^\top를 보자. Eckart–Young–Mirsky 정리: rank⁡B≤k\operatorname{rank}B \le k인 모든 BB에 대해

∥A−B∥2≥σk+1=∥A−Ak∥2,∥A−B∥F≥(∑i>kσi2)1/2=∥A−Ak∥F.\|A - B\|_2 \ge \sigma_{k+1} = \|A - A_k\|_2, \qquad \|A - B\|_F \ge \Big(\sum_{i>k}\sigma_i^2\Big)^{1/2} = \|A - A_k\|_F .

증명(spectral 경우). null⁡(B)\operatorname{null}(B)의 차원은 n−kn-k 이상이고 span⁡(v1,…,vk+1)\operatorname{span}(v_1,\dots,v_{k+1})의 차원은 k+1k+1이므로, Rn\mathbb R^n 안에서 둘은 단위벡터 ww를 공유해야 한다. 그러면 ∥(A−B)w∥=∥Aw∥=(∑i≤k+1σi2(vi⊤w)2)1/2≥σk+1\|(A-B)w\| = \|Aw\| = \big(\sum_{i\le k+1}\sigma_i^2 (v_i^\top w)^2\big)^{1/2} \ge \sigma_{k+1}이다. A−Ak=∑i>kσiuivi⊤A - A_k = \sum_{i>k}\sigma_i u_iv_i^\top이므로 절단 SVD가 이 하한을 달성한다. 즉 특이값 스펙트럼이 곧 압축 가능성 곡선이다.

매개변수params k(m+n) – / mn = 4096 ‖A−Ak‖F/‖A‖F – √(Σi>kσi²)/‖A‖F – ‖A−Ak‖2 = σk+1 –
Slide k: the right image keeps only the top k singular triplets, Ak = Σi≤k σiuiviᵀ. The two error read-outs agree to every digit — that is Eckart–Young: no rank-k matrix does better, and the error is exactly the tail of the spectrum. In the image, axis-aligned blocks are captured by a few terms and the smooth diagonal stripes by just two (sin(a+b) = sin a cos b + cos a sin b is a sum of two outer products), while the disc and the triangle's sharp diagonal edge need many. Switch the source: a weight with a decaying spectrum compresses well (LoRA, MLA), pure noise does not — its spectrum is flat and the error falls almost linearly. k를 바꿔 보세요. 오른쪽 이미지는 상위 k개의 특이 삼중쌍만 남긴 Ak = Σi≤k σiuiviᵀ이다. 두 오차 값이 자릿수까지 같다. 이것이 Eckart–Young 정리다. 어떤 rank k 행렬도 이보다 나을 수 없고, 오차는 정확히 스펙트럼의 꼬리다. 이미지에서 축에 나란한 사각형은 몇 항으로, 매끄러운 대각선 줄무늬는 단 두 항으로 잡히지만(sin(a+b) = sin a cos b + cos a sin b는 외적 두 개의 합이다), 원과 삼각형의 날카로운 대각선 경계는 많은 항이 필요하다. 원본을 바꿔 보면, 스펙트럼이 감쇠하는 weight는 잘 압축되고(LoRA, MLA) 순수 잡음은 그렇지 않다. 스펙트럼이 평평해서 오차가 거의 직선으로 줄어든다.

A rank-kk factorization Ak=(UkΣk)Vk⊤A_k = (U_k\Sigma_k)V_k^\top stores k(m+n)k(m+n) numbers instead of mnmn. That trade is behind three methods used later. LoRA freezes WW and learns ΔW=BA\Delta W = BA with B∈Rm×rB\in\mathbb R^{m\times r}, A∈Rr×nA\in\mathbb R^{r\times n}, betting that the fine-tuning update has a fast-decaying spectrum. MLA caches a dcd_c-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 dcd_c. PCA keeps the top right singular vectors of centred data, which are the top eigenvectors of its covariance.

The condition number

For invertible AA, κ(A)=σmax⁡/σmin⁡\kappa(A) = \sigma_{\max}/\sigma_{\min} (for SPD matrices, λmax⁡/λmin⁡\lambda_{\max}/\lambda_{\min}). It bounds error amplification: if Ax=bAx = b and A(x+δx)=b+δbA(x+\delta x) = b+\delta b, then ∥δx∥≤∥δb∥/σmin⁡\|\delta x\| \le \|\delta b\|/\sigma_{\min} and ∥b∥≤σmax⁡∥x∥\|b\| \le \sigma_{\max}\|x\|, so

∥δx∥∥x∥≤κ(A) ∥δb∥∥b∥.\frac{\|\delta x\|}{\|x\|} \le \kappa(A)\,\frac{\|\delta b\|}{\|b\|}.

The same number sets optimisation speed: on a quadratic with Hessian HH, GD at its best fixed step contracts the error by (κ−1)/(κ+1)(\kappa-1)/(\kappa+1) per step (gradient descent). Orthogonal matrices have κ=1\kappa = 1, the best possible — one reading of why Muon’s orthogonalised update is well-behaved.

Least squares and the pseudo-inverse

Minimise ∥Xθ−y∥2\|X\theta - y\|^2. The gradient 2X⊤(Xθ−y)2X^\top(X\theta - y) vanishes at the normal equations X⊤Xθ=X⊤yX^\top X\theta = X^\top y. With the thin SVD X=UΣV⊤X = U\Sigma V^\top and full column rank,

θ⋆=(VΣ2V⊤)−1VΣU⊤y=VΣ−1U⊤y=X+y,\theta^\star = (V\Sigma^2V^\top)^{-1}V\Sigma U^\top y = V\Sigma^{-1}U^\top y = X^+ y ,

and the fit Xθ⋆=UU⊤yX\theta^\star = UU^\top y is the orthogonal projection of yy onto the column space. The pseudo-inverse X+=VΣ+U⊤X^+ = V\Sigma^{+}U^\top (invert the nonzero σi\sigma_i, 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 X⊤XX^\top X when XX is ill-conditioned: κ(X⊤X)=κ(X)2\kappa(X^\top X) = \kappa(X)^2, so a 10710^7 condition number becomes 101410^{14}, 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 UV⊤UV^\top, LoRA’s parameter count and a Hessian eigenvalue from Hessian-vector products.

NumPy Spectral theorem, power iteration, SVD, Eckart–Young
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}")
 
NumPy Least squares, pseudo-inverse and the condition number
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")
 
NumPy Uses: PCA, Newton–Schulz polar factor, LoRA, Hessian eigenvalue
# --- 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}")
 
확인 문제Check yourself

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: ∥A−A2∥2=σ3=2\|A - A_2\|_2 = \sigma_3 = 2 and ∥A−A2∥F=σ32+σ42=4+1=5\|A - A_2\|_F = \sqrt{\sigma_3^2 + \sigma_4^2} = \sqrt{4 + 1} = \sqrt5. No other rank-2 matrix does better in either norm.

확인 문제Check yourself

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)?

κ(X⊤X)=κ(X)2=1010\kappa(X^\top X) = \kappa(X)^2 = 10^{10}, and a backward-stable solve loses about log⁡10κ\log_{10}\kappa digits, so about 10 of 16. An SVD- or QR-based solver works with XX 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; Ak=PΛkP−1A^k = P\Lambda^kP^{-1} means repeated maps are governed by ∣λi∣|\lambda_i|, and power iteration finds the top one at rate ∣λ2/λ1∣|\lambda_2/\lambda_1|.
  • Symmetric matrices have real eigenvalues and orthonormal eigenvectors: S=QΛQ⊤S = Q\Lambda Q^\top, x⊤Sx=∑λi(qi⊤x)2x^\top Sx = \sum\lambda_i(q_i^\top x)^2.
  • Every matrix is rotate–scale–rotate, A=UΣV⊤A = U\Sigma V^\top; σ1=∥A∥2\sigma_1 = \|A\|_2, ∑σi2=∥A∥F2\sum\sigma_i^2 = \|A\|_F^2, orthogonal ⇔ all σi=1\sigma_i = 1.
  • Truncated SVD is the best rank-kk approximation in both norms; the spectrum’s tail is the error. LoRA, MLA and PCA are this.
  • κ=σmax⁡/σmin⁡\kappa = \sigma_{\max}/\sigma_{\min} bounds error amplification and GD speed; normal equations square it, the pseudo-inverse VΣ+U⊤V\Sigma^+U^\top avoids that and gives minimum-norm solutions.

Where this is used

rank kk 분해 Ak=(UkΣk)Vk⊤A_k = (U_k\Sigma_k)V_k^\top는 mnmn개 대신 k(m+n)k(m+n)개의 숫자를 저장한다. 이 거래가 뒤에서 쓰이는 세 방법의 바탕이다. LoRA는 WW를 얼리고 ΔW=BA\Delta W = BA(B∈Rm×rB\in\mathbb R^{m\times r}, A∈Rr×nA\in\mathbb R^{r\times n})를 학습한다. 미세조정 업데이트의 스펙트럼이 빨리 감쇠한다는 데 거는 것이다. MLA는 token마다 dcd_c차원 latent(와 작은 decoupled RoPE key)를 캐시하고 up-projection으로 key와 value를 복원한다. 즉 쌓아 놓은 KV projection을 rank dcd_c로 제한한다. PCA는 중심화한 데이터의 상위 오른쪽 특이벡터, 즉 공분산의 상위 고유벡터를 남긴다.

조건수

가역 행렬 AA에 대해 κ(A)=σmax⁡/σmin⁡\kappa(A) = \sigma_{\max}/\sigma_{\min}이다(SPD 행렬이면 λmax⁡/λmin⁡\lambda_{\max}/\lambda_{\min}). 이것이 오차 증폭을 묶는다. Ax=bAx = b이고 A(x+δx)=b+δbA(x+\delta x) = b+\delta b이면 ∥δx∥≤∥δb∥/σmin⁡\|\delta x\| \le \|\delta b\|/\sigma_{\min}, ∥b∥≤σmax⁡∥x∥\|b\| \le \sigma_{\max}\|x\|이므로

∥δx∥∥x∥≤κ(A) ∥δb∥∥b∥.\frac{\|\delta x\|}{\|x\|} \le \kappa(A)\,\frac{\|\delta b\|}{\|b\|}.

같은 숫자가 최적화 속도도 정한다. Hessian이 HH인 이차 함수에서 가장 좋은 고정 step의 GD는 step마다 오차를 (κ−1)/(κ+1)(\kappa-1)/(\kappa+1)배로 줄인다(경사하강법). 직교 행렬은 가능한 최선인 κ=1\kappa = 1이다. Muon의 직교화된 업데이트가 다루기 좋은 이유를 읽는 한 가지 방법이다.

최소제곱과 유사역행렬

∥Xθ−y∥2\|X\theta - y\|^2를 최소화하자. gradient 2X⊤(Xθ−y)2X^\top(X\theta - y)가 0이 되는 곳이 정규방정식(normal equations) X⊤Xθ=X⊤yX^\top X\theta = X^\top y다. thin SVD X=UΣV⊤X = U\Sigma V^\top, 열 rank가 꽉 찼다면

θ⋆=(VΣ2V⊤)−1VΣU⊤y=VΣ−1U⊤y=X+y\theta^\star = (V\Sigma^2V^\top)^{-1}V\Sigma U^\top y = V\Sigma^{-1}U^\top y = X^+ y

이고, 적합값 Xθ⋆=UU⊤yX\theta^\star = UU^\top y는 yy를 열공간에 직교 사영한 것이다. 유사역행렬(pseudo-inverse) X+=VΣ+U⊤X^+ = V\Sigma^{+}U^\top(0 아닌 σi\sigma_i만 뒤집고 0은 그대로)는 rank가 부족하거나 미지수가 더 많은 경우도 다루며, 그때는 최소 노름 해를 준다. 영공간 성분은 길이만 늘리기 때문이다. 수치적으로는 XX의 조건이 나쁠 때 X⊤XX^\top X를 절대 만들지 말자. κ(X⊤X)=κ(X)2\kappa(X^\top X) = \kappa(X)^2이라서 조건수 10710^7이 101410^{14}가 되고, 이는 float64의 한계에 닿는다.

직접 구현하기

블록 셋. 고유분해·SVD 항등식과 power iteration, 최소제곱·유사역행렬·조건수, 그리고 쓰임새: PCA, UV⊤UV^\top를 위한 Newton–Schulz, LoRA의 매개변수 수, Hessian-vector product로 구하는 Hessian 고유값.

NumPy 스펙트럼 정리, power iteration, SVD, Eckart–Young
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}")
 
NumPy 최소제곱, 유사역행렬, 조건수
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")
 
NumPy 쓰임새: PCA, Newton–Schulz polar factor, LoRA, Hessian 고유값
# --- 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}")
 
확인 문제Check yourself

특이값이 10, 4, 2, 1인 행렬이 있다. 최선의 rank 2 근사의 spectral 노름 오차와 Frobenius 노름 오차는?

Eckart–Young: ∥A−A2∥2=σ3=2\|A - A_2\|_2 = \sigma_3 = 2, ∥A−A2∥F=σ32+σ42=4+1=5\|A - A_2\|_F = \sqrt{\sigma_3^2 + \sigma_4^2} = \sqrt{4 + 1} = \sqrt5. 어떤 다른 rank 2 행렬도 두 노름 모두에서 이보다 나을 수 없다.

확인 문제Check yourself

설계 행렬 X의 조건수가 1e5다. float64(유효숫자 약 16자리)에서 정규방정식 XᵀXθ = Xᵀy를 풀면 유효숫자를 대략 몇 자리 잃을 수 있나?

κ(X⊤X)=κ(X)2=1010\kappa(X^\top X) = \kappa(X)^2 = 10^{10}이고, backward-stable한 풀이는 대략 log⁡10κ\log_{10}\kappa자리를 잃으므로 16자리 중 약 10자리다. SVD나 QR 기반 풀이는 XX를 직접 다루므로 잔차가 작으면 약 5자리만 잃는다. float32(약 7자리)라면 정규방정식은 잡음을 돌려준다.

정리

  • 고유벡터는 자기 직선 위에 머문다. Ak=PΛkP−1A^k = P\Lambda^kP^{-1}이므로 반복 사상은 ∣λi∣|\lambda_i|가 지배하고, power iteration은 ∣λ2/λ1∣|\lambda_2/\lambda_1|의 속도로 최상위 고유벡터를 찾는다.
  • 대칭 행렬은 실수 고유값과 정규직교 고유벡터를 갖는다. S=QΛQ⊤S = Q\Lambda Q^\top, x⊤Sx=∑λi(qi⊤x)2x^\top Sx = \sum\lambda_i(q_i^\top x)^2.
  • 모든 행렬은 회전-배율-회전 A=UΣV⊤A = U\Sigma V^\top이다. σ1=∥A∥2\sigma_1 = \|A\|_2, ∑σi2=∥A∥F2\sum\sigma_i^2 = \|A\|_F^2, 직교 ⇔ 모든 σi=1\sigma_i = 1.
  • 절단 SVD는 두 노름 모두에서 최선의 rank kk 근사이고, 스펙트럼의 꼬리가 곧 오차다. LoRA, MLA, PCA가 이것이다.
  • κ=σmax⁡/σmin⁡\kappa = \sigma_{\max}/\sigma_{\min}은 오차 증폭과 GD 속도를 묶는다. 정규방정식은 이를 제곱하고, 유사역행렬 VΣ+U⊤V\Sigma^+U^\top는 그것을 피하며 최소 노름 해를 준다.

이 사이트에서 쓰이는 곳

더 읽을거리Further reading