Track 0 · Math Foundations · 01/10

벡터·행렬·텐서Vectors, matrices and tensors

행렬을 "숫자 표"가 아니라 선형 사상으로 읽고, 내적·노름·행렬곱·텐서 shape·einsum·broadcasting을 이후 attention, MoE, Muon 레슨이 쓰는 그대로 손에 익힌다.Read a matrix as a linear map rather than a table of numbers, and get fluent with the inner products, norms, matrix products, tensor shapes, einsum and broadcasting that the attention, MoE and Muon lessons use.

40 분min linear algebra · dot product · norm · matrix multiplication · einsum · broadcasting · tensor shapes

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 a,b∈Rda, b \in \mathbb R^d, a⊤b=∑iaibi=∥a∥2∥b∥2cos⁡θa^\top b = \sum_i a_i b_i = \|a\|_2\|b\|_2\cos\theta. Geometrically, a⊤b/∥a∥2a^\top b / \|a\|_2 is the signed length of bb‘s shadow on the direction of aa, and the projection of bb onto the line through aa is

proj⁡ab=a⊤ba⊤a a.\operatorname{proj}_a b = \frac{a^\top b}{a^\top a}\, a .

(Check: the residual b−proj⁡abb - \operatorname{proj}_a b is orthogonal to aa, since a⊤b−a⊤ba⊤aa⊤a=0a^\top b - \frac{a^\top b}{a^\top a}a^\top a = 0.) Cauchy–Schwarz, ∣a⊤b∣≤∥a∥2∥b∥2|a^\top b| \le \|a\|_2\|b\|_2, is what makes cos⁡θ∈[−1,1]\cos\theta \in [-1, 1] well defined. Dividing out the lengths gives cosine similarity, cos⁡θ=a⊤b/(∥a∥∥b∥)\cos\theta = a^\top b/(\|a\|\|b\|), the standard similarity for embeddings and retrieval.

An attention logit is a raw dot product q⊤kq^\top k, so it mixes alignment (cos⁡θ\cos\theta) with length. If the entries of qq and kk are independent with mean 0 and variance 1,

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

so logits grow like d\sqrt d and the softmax saturates. Scaled dot-product attention divides by d\sqrt d to undo exactly this. QK-norm goes further and normalises qq and kk, so the logit is mostly a scaled cosine.

A matrix is a linear map

A matrix A∈Rm×nA \in \mathbb R^{m\times n} is the linear map x↦Axx \mapsto Ax from Rn\mathbb R^n to Rm\mathbb R^m, and it is completely determined by where it sends the basis vectors: column jj of AA is AejAe_j. Two ways to read AxAx:

Ax=∑jxj a:,j⏟column view: mix the columns(Ax)i=ai,:⊤x⏟row view: m dot products\underbrace{Ax = \sum_j x_j\, a_{:,j}}_{\text{column view: mix the columns}} \qquad\qquad \underbrace{(Ax)_i = a_{i,:}^\top x}_{\text{row view: } m \text{ dot products}}

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

a,b∈Rda, b \in \mathbb R^d에 대해 a⊤b=∑iaibi=∥a∥2∥b∥2cos⁡θa^\top b = \sum_i a_i b_i = \|a\|_2\|b\|_2\cos\theta이다. 기하학적으로 a⊤b/∥a∥2a^\top b / \|a\|_2는 bb가 aa 방향에 드리우는 그림자의 부호 있는 길이이고, aa를 지나는 직선으로의 사영은 다음과 같다.

proj⁡ab=a⊤ba⊤a a.\operatorname{proj}_a b = \frac{a^\top b}{a^\top a}\, a .

(확인: 잔차 b−proj⁡abb - \operatorname{proj}_a b는 aa와 직교한다. a⊤b−a⊤ba⊤aa⊤a=0a^\top b - \frac{a^\top b}{a^\top a}a^\top a = 0이기 때문이다.) 코시–슈바르츠 부등식(Cauchy–Schwarz) ∣a⊤b∣≤∥a∥2∥b∥2|a^\top b| \le \|a\|_2\|b\|_2 덕분에 cos⁡θ∈[−1,1]\cos\theta \in [-1, 1]이 잘 정의된다. 길이를 나눠 없애면 코사인 유사도(cosine similarity) cos⁡θ=a⊤b/(∥a∥∥b∥)\cos\theta = a^\top b/(\|a\|\|b\|)가 되고, embedding과 검색에서 표준으로 쓰는 유사도다.

attention logit은 날것의 내적 q⊤kq^\top k라서 정렬 정도(cos⁡θ\cos\theta)와 길이가 섞여 있다. qq, kk의 성분이 서로 독립이고 평균 0, 분산 1이면

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

이므로 logit은 d\sqrt d에 비례해 커지고 softmax가 포화된다. scaled dot-product attention이 d\sqrt d로 나누는 것은 정확히 이것을 되돌리기 위해서다. QK-norm은 한 걸음 더 나가 qq, kk를 정규화해서 logit을 사실상 배율이 곱해진 코사인으로 만든다.

행렬은 선형 사상이다

행렬 A∈Rm×nA \in \mathbb R^{m\times n}은 Rn\mathbb R^n에서 Rm\mathbb R^m으로 가는 선형 사상 x↦Axx \mapsto Ax이고, 기저 벡터를 어디로 보내는지만 알면 완전히 정해진다. AA의 jj번째 열이 AejAe_j다. AxAx를 읽는 두 가지 방법:

Ax=∑jxj a:,j⏟열 관점: 열들을 섞는다(Ax)i=ai,:⊤x⏟행 관점: 내적 m개\underbrace{Ax = \sum_j x_j\, a_{:,j}}_{\text{열 관점: 열들을 섞는다}} \qquad\qquad \underbrace{(Ax)_i = a_{i,:}^\top x}_{\text{행 관점: 내적 } m \text{개}}

행 관점은 Linear layer가 출력 unit마다 계산하는 것이고, 머릿속에 그릴 때는 열 관점을 쓴다.

det – 면적 배율area factor |det| –
Drag the red and green tips: they are where e₁ and e₂ land, i.e. the two columns of A. Every other point follows, because Ax = x₁·(column 1) + x₂·(column 2) — drag the purple x and watch Ax (dashed) built from that sum. The shaded square becomes a parallelogram of signed area det A (it turns red when orientation flips); the unit circle becomes an ellipse. Pick a B to see the product as composition: B·A means "A first, then B", and swapping the order usually changes the picture. 빨강·초록 끝점을 끌어 보세요. e₁, e₂가 가는 곳, 즉 A의 두 열이다. Ax = x₁·(1열) + x₂·(2열)이므로 나머지 모든 점이 따라 움직인다. 보라색 x를 끌면 그 합으로 만들어지는 Ax(점선)를 볼 수 있다. 색칠된 단위 정사각형은 부호 있는 넓이 det A의 평행사변형이 되고(방향이 뒤집히면 빨강), 단위원은 타원이 된다. B를 고르면 곱 = 합성을 볼 수 있다. B·A는 "A 먼저, 그다음 B"이고, 순서를 바꾸면 대개 그림이 달라진다.

Composition is the product. Apply AA then BB: B(Ax)=∑kB:,k(Ax)k=∑kB:,k∑jAkjxjB(Ax) = \sum_k B_{:,k}(Ax)_k = \sum_k B_{:,k}\sum_j A_{kj}x_j, so the matrix of the composite map has entries

(BA)ij=∑kBikAkj.(BA)_{ij} = \sum_k B_{ik}A_{kj}.

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 A∈Rm×rA\in\mathbb R^{m\times r}, B∈Rr×nB\in\mathbb R^{r\times n} and a vector xx, A(Bx)A(Bx) costs r(m+n)r(m+n) multiply-adds while (AB)x(AB)x costs mrn+mnmrn + mn. LoRA’s W+BAW + BA is applied as Wx+B(Ax)Wx + B(Ax) 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 aka_k the columns of AA and bk⊤b_k^\top the rows of BB,

AB=∑kakbk⊤,AB = \sum_{k} a_k b_k^\top ,

a sum of rank-1 matrices. Linear attention’s state St=∑s≤tksvs⊤S_t = \sum_{s\le t} k_s v_s^\top is exactly this, built one outer product per token.

Determinant. In 2-D, det⁡A\det A is the signed area of the parallelogram spanned by the columns — the factor by which AA scales every area, negative when it flips orientation. Since areas scale successively, det⁡(BA)=det⁡B det⁡A\det(BA) = \det B\,\det A. det⁡A=0\det A = 0 means the columns are dependent: the map squashes the plane onto a line (pick “rank 1”), some nonzero xx has Ax=0Ax = 0, and no inverse can undo it. In general rank is the dimension of the column space {Ax}\{Ax\}; n−rank⁡n - \operatorname{rank} is the dimension of the null space.

Transpose is the adjoint. ⟨Ax,y⟩=x⊤A⊤y=⟨x,A⊤y⟩\langle Ax, y\rangle = x^\top A^\top y = \langle x, A^\top y\rangle. When a layer computes y=Wxy = Wx and the loss sends back ∂L/∂y\partial L/\partial y, the signal that reaches xx is W⊤∂L/∂yW^\top \partial L/\partial y — backprop multiplies by transposes because of this identity (calculus lesson).

Norms: how big, and in which geometry

A norm measures size: ∥x∥≥0\|x\| \ge 0 with equality only at 0, ∥cx∥=∣c∣ ∥x∥\|cx\| = |c|\,\|x\|, and the triangle inequality. The ℓp\ell_p family is ∥x∥p=(∑i∣xi∣p)1/p\|x\|_p = (\sum_i |x_i|^p)^{1/p}, with ℓ1\ell_1 (sum of magnitudes), ℓ2\ell_2 (Euclidean) and ℓ∞=max⁡i∣xi∣\ell_\infty = \max_i |x_i|. In Rn\mathbb R^n,

∥x∥∞≤∥x∥2≤∥x∥1≤n ∥x∥2,∥x∥2≤n ∥x∥∞.\|x\|_\infty \le \|x\|_2 \le \|x\|_1 \le \sqrt n\,\|x\|_2, \qquad \|x\|_2 \le \sqrt n\,\|x\|_\infty .

RMSNorm uses rms⁡(x)=∥x∥2/d\operatorname{rms}(x) = \|x\|_2/\sqrt d, the ℓ2\ell_2 norm rescaled so it does not grow with width.

Each norm has a dual ∥g∥∗=max⁡∥d∥≤1g⊤d\|g\|_* = \max_{\|d\|\le 1} g^\top d, and Hölder’s inequality g⊤d≤∥g∥q∥d∥pg^\top d \le \|g\|_q\|d\|_p (with 1/p+1/q=11/p + 1/q = 1) says the dual of ℓp\ell_p is ℓq\ell_q: ℓ2\ell_2 is self-dual, ℓ1\ell_1 and ℓ∞\ell_\infty are dual to each other. The maximiser is the steepest-ascent direction under that norm — the first-order Taylor model L(θ+d)≈L(θ)+g⊤dL(\theta+d)\approx L(\theta)+g^\top d is decreased fastest by −d⋆-d^\star. Change the ruler and the best step changes:

합성이 곧 곱이다. AA를 하고 BB를 하면 B(Ax)=∑kB:,k(Ax)k=∑kB:,k∑jAkjxjB(Ax) = \sum_k B_{:,k}(Ax)_k = \sum_k B_{:,k}\sum_j A_{kj}x_j이므로 합성 사상의 행렬 성분은

(BA)ij=∑kBikAkj(BA)_{ij} = \sum_k B_{ik}A_{kj}

이다. 행렬곱이 이렇게 정의된 이유가 이것이다. 합성이 그렇듯 결합법칙은 성립하지만 교환법칙은 성립하지 않는다. 그림에서 보듯 회전 후 밀림과 밀림 후 회전은 다르다. 결합법칙에는 계속 등장하는 비용 결과가 따른다. A∈Rm×rA\in\mathbb R^{m\times r}, B∈Rr×nB\in\mathbb R^{r\times n}, 벡터 xx에 대해 A(Bx)A(Bx)는 곱셈-덧셈 r(m+n)r(m+n)번, (AB)x(AB)x는 mrn+mnmrn + mn번이다. LoRA의 W+BAW + BA를 Wx+B(Ax)Wx + B(Ax)로 적용하는 이유이고, MLA의 “absorb” 기법은 같은 괄호를 반대로 옮긴 것이다.

곱을 전개하는 두 번째 방법은 외적(outer product) 의 합이다. aka_k를 AA의 열, bk⊤b_k^\top를 BB의 행이라 하면

AB=∑kakbk⊤AB = \sum_{k} a_k b_k^\top

즉 rank 1 행렬들의 합이다. linear attention의 상태 St=∑s≤tksvs⊤S_t = \sum_{s\le t} k_s v_s^\top가 정확히 이것이고, token마다 외적 하나씩 쌓아 만든다.

행렬식(determinant). 2차원에서 det⁡A\det A는 두 열이 만드는 평행사변형의 부호 있는 넓이, 즉 AA가 모든 넓이에 곱하는 배율이다. 방향을 뒤집으면 음수가 된다. 넓이가 차례로 곱해지므로 det⁡(BA)=det⁡B det⁡A\det(BA) = \det B\,\det A이다. det⁡A=0\det A = 0이면 열들이 일차종속이다. 사상이 평면을 한 직선으로 누르고(“rank 1”을 골라 보자), Ax=0Ax = 0인 0 아닌 xx가 있으며, 어떤 역사상도 이를 되돌릴 수 없다. 일반적으로 rank는 열공간 {Ax}\{Ax\}의 차원이고 n−rank⁡n - \operatorname{rank}가 영공간(null space)의 차원이다.

전치는 수반(adjoint)이다. ⟨Ax,y⟩=x⊤A⊤y=⟨x,A⊤y⟩\langle Ax, y\rangle = x^\top A^\top y = \langle x, A^\top y\rangle. layer가 y=Wxy = Wx를 계산하고 손실이 ∂L/∂y\partial L/\partial y를 돌려보내면 xx에 도달하는 신호는 W⊤∂L/∂yW^\top \partial L/\partial y다. 역전파가 전치를 곱하는 이유가 이 항등식이다(미분 레슨).

노름: 얼마나 큰가, 어떤 기하로 재는가

노름(norm)은 크기를 잰다. ∥x∥≥0\|x\| \ge 0이고 0에서만 등호, ∥cx∥=∣c∣ ∥x∥\|cx\| = |c|\,\|x\|, 그리고 삼각부등식. ℓp\ell_p 노름은 ∥x∥p=(∑i∣xi∣p)1/p\|x\|_p = (\sum_i |x_i|^p)^{1/p}이고 ℓ1\ell_1(절댓값의 합), ℓ2\ell_2(유클리드), ℓ∞=max⁡i∣xi∣\ell_\infty = \max_i |x_i|가 대표적이다. Rn\mathbb R^n에서

∥x∥∞≤∥x∥2≤∥x∥1≤n ∥x∥2,∥x∥2≤n ∥x∥∞.\|x\|_\infty \le \|x\|_2 \le \|x\|_1 \le \sqrt n\,\|x\|_2, \qquad \|x\|_2 \le \sqrt n\,\|x\|_\infty .

RMSNorm은 rms⁡(x)=∥x∥2/d\operatorname{rms}(x) = \|x\|_2/\sqrt d, 즉 폭(width)에 따라 커지지 않도록 다시 스케일한 ℓ2\ell_2 노름을 쓴다.

모든 노름에는 쌍대 노름(dual norm) ∥g∥∗=max⁡∥d∥≤1g⊤d\|g\|_* = \max_{\|d\|\le 1} g^\top d가 있고, 횔더 부등식(Hölder) g⊤d≤∥g∥q∥d∥pg^\top d \le \|g\|_q\|d\|_p(1/p+1/q=11/p + 1/q = 1)는 ℓp\ell_p의 쌍대가 ℓq\ell_q임을 말한다. ℓ2\ell_2는 자기 자신이 쌍대이고 ℓ1\ell_1과 ℓ∞\ell_\infty는 서로 쌍대다. 최댓값을 주는 dd가 그 노름으로 잰 최급상승 방향이다. 1차 테일러 모델 L(θ+d)≈L(θ)+g⊤dL(\theta+d)\approx L(\theta)+g^\top d를 가장 빨리 줄이는 것이 −d⋆-d^\star다. 자를 바꾸면 최선의 step이 바뀐다.

‖g‖₁ – ‖g‖₂ – ‖g‖∞ – d* – g·d* = ‖g‖q – cos(g, d*) –
Drag the blue gradient g and slide p. The shaded set is the ℓp unit ball ‖d‖p ≤ 1 (faint outlines: ℓ₁ diamond, ℓ₂ circle, ℓ∞ square). The amber arrow is the unit step that increases g·d the most; the dashed supporting line touches the ball there, at height ‖g‖q with 1/p + 1/q = 1. Only for p = 2 does the best step point along g. At p = ∞ it snaps to a corner, sign(g) — sign descent, the core of Adam; at p = 1 it snaps to the single largest coordinate. 파란 gradient g를 끌고 p를 바꿔 보세요. 색칠된 영역이 ℓp 단위공 ‖d‖p ≤ 1이다(옅은 선: ℓ₁ 마름모, ℓ₂ 원, ℓ∞ 정사각형). 주황 화살표는 g·d를 가장 크게 하는 단위 step이고, 점선 지지선이 그 점에서 공에 닿는다. 그 높이가 ‖g‖q(1/p + 1/q = 1)다. best step이 g 방향인 것은 p = 2일 때뿐이다. p = ∞이면 모서리 sign(g)로 튀고(sign descent, Adam의 핵심), p = 1이면 가장 큰 좌표 하나로 튄다.

The closed forms: for p=2p = 2, d⋆=g/∥g∥2d^\star = g/\|g\|_2; for p=∞p=\infty, d⋆=sign⁡(g)d^\star = \operatorname{sign}(g) and g⊤d⋆=∥g∥1g^\top d^\star = \|g\|_1; for p=1p = 1, d⋆=sign⁡(gk)ekd^\star = \operatorname{sign}(g_k)e_k with k=arg⁡max⁡i∣gi∣k = \arg\max_i |g_i|. For 1<p<∞1 < p < \infty, di⋆=sign⁡(gi) ∣gi∣q−1/∥g∥qq−1d^\star_i = \operatorname{sign}(g_i)\,|g_i|^{q-1}/\|g\|_q^{q-1} (plug in to check ∥d⋆∥p=1\|d^\star\|_p = 1 and g⊤d⋆=∥g∥qg^\top d^\star = \|g\|_q). Adam with its averages switched off (β1=β2=0\beta_1=\beta_2=0) divides gg by ∣g∣|g| — the ℓ∞\ell_\infty row. The Muon lesson repeats this table for matrices, where the spectral norm gives UV⊤UV^\top.

Matrix norms. Two matter most. The Frobenius norm treats the matrix as a long vector: ∥A∥F=(∑ijAij2)1/2=tr⁡(A⊤A)\|A\|_F = (\sum_{ij}A_{ij}^2)^{1/2} = \sqrt{\operatorname{tr}(A^\top A)}. The operator (spectral) norm measures the largest stretch, ∥A∥2=max⁡x≠0∥Ax∥2/∥x∥2\|A\|_2 = \max_{x\ne 0}\|Ax\|_2/\|x\|_2 — the long semi-axis of the amber ellipse in the first figure, i.e. the largest singular value (next lesson). By definition ∥Ax∥≤∥A∥2∥x∥\|Ax\|\le\|A\|_2\|x\|, which gives submultiplicativity ∥AB∥2≤∥A∥2∥B∥2\|AB\|_2 \le \|A\|_2\|B\|_2: a product of LL layers can stretch a signal by up to ∏l∥Wl∥2\prod_l\|W_l\|_2, the root of exploding and vanishing signals in deep nets and RNNs. They compare as ∥A∥2≤∥A∥F≤rank⁡A ∥A∥2\|A\|_2 \le \|A\|_F \le \sqrt{\operatorname{rank}A}\,\|A\|_2.

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 sbhts=∑dqbhtd kbhsds_{bhts} = \sum_d q_{bhtd}\,k_{bhsd}, i.e. QK⊤QK^\top per batch and head. The cost of a two-operand einsum is one multiply-add per combination of all indices, so FLOPs =2∏all lettersnℓ= 2\prod_{\text{all letters}} n_\ell.

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.

닫힌 꼴은 다음과 같다. p=2p = 2이면 d⋆=g/∥g∥2d^\star = g/\|g\|_2, p=∞p=\infty이면 d⋆=sign⁡(g)d^\star = \operatorname{sign}(g)이고 g⊤d⋆=∥g∥1g^\top d^\star = \|g\|_1, p=1p = 1이면 k=arg⁡max⁡i∣gi∣k = \arg\max_i |g_i|에 대해 d⋆=sign⁡(gk)ekd^\star = \operatorname{sign}(g_k)e_k. 1<p<∞1 < p < \infty이면 di⋆=sign⁡(gi) ∣gi∣q−1/∥g∥qq−1d^\star_i = \operatorname{sign}(g_i)\,|g_i|^{q-1}/\|g\|_q^{q-1}이다(대입해서 ∥d⋆∥p=1\|d^\star\|_p = 1, g⊤d⋆=∥g∥qg^\top d^\star = \|g\|_q를 확인해 보자). 이동평균을 끈 Adam(β1=β2=0\beta_1=\beta_2=0)은 gg를 ∣g∣|g|로 나누므로 ℓ∞\ell_\infty 줄에 해당한다. Muon 레슨은 이 표를 행렬에 대해 다시 만들고, 거기서는 spectral norm이 UV⊤UV^\top를 준다.

행렬 노름. 둘이 가장 중요하다. Frobenius 노름은 행렬을 긴 벡터로 본다. ∥A∥F=(∑ijAij2)1/2=tr⁡(A⊤A)\|A\|_F = (\sum_{ij}A_{ij}^2)^{1/2} = \sqrt{\operatorname{tr}(A^\top A)}. 연산자(spectral) 노름은 가장 크게 늘이는 배율이다. ∥A∥2=max⁡x≠0∥Ax∥2/∥x∥2\|A\|_2 = \max_{x\ne 0}\|Ax\|_2/\|x\|_2. 첫 그림의 주황 타원의 긴 반축, 즉 가장 큰 특이값이다(다음 레슨). 정의에서 바로 ∥Ax∥≤∥A∥2∥x∥\|Ax\|\le\|A\|_2\|x\|이고, 여기서 곱에 대한 부등식 ∥AB∥2≤∥A∥2∥B∥2\|AB\|_2 \le \|A\|_2\|B\|_2가 나온다. LL개 layer의 곱은 신호를 최대 ∏l∥Wl∥2\prod_l\|W_l\|_2배까지 늘일 수 있다. 깊은 망과 RNN에서 신호가 폭발하거나 소실되는 뿌리다. 둘 사이에는 ∥A∥2≤∥A∥F≤rank⁡A ∥A∥2\|A\|_2 \le \|A\|_F \le \sqrt{\operatorname{rank}A}\,\|A\|_2가 성립한다.

텐서와 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'는 sbhts=∑dqbhtd kbhsds_{bhts} = \sum_d q_{bhtd}\,k_{bhsd}, 즉 batch·head마다 QK⊤QK^\top이다. 두 피연산자 einsum의 비용은 모든 index 조합마다 곱셈-덧셈 한 번이므로 FLOPs =2∏모든 글자nℓ= 2\prod_{\text{모든 글자}} n_\ell이다.

Broadcasting은 shape이 다른 배열 사이에서도 원소별 연산이 되게 한다. shape을 오른쪽부터 맞추고, 각 쌍의 크기가 같거나 한쪽이 1이어야 한다(없는 축은 1로 친다). 크기 1인 축은 복사 없이 늘어난다.

einsum
broadcasting
Pick an einsum or type your own and change the sizes. Letters that appear in an input but not in the output are summed; letters in every operand and the output are batch dimensions. The cost of a two-operand einsum is 2 × (product of all index sizes) FLOPs — every index, once. Below, shapes are aligned from the right; each pair must be equal or contain a 1. The first preset is the most common silent bug: it does not fail, it makes an N×N matrix. einsum을 고르거나 직접 입력하고 크기를 바꿔 보세요. 입력에는 있고 출력에는 없는 글자는 합해지는(contracted) 축, 모든 피연산자와 출력에 있는 글자는 batch 축이다. 두 피연산자 einsum의 비용은 2 × (모든 index 크기의 곱) FLOPs다. 모든 index를 한 번씩 곱한다. 아래는 broadcasting. shape을 오른쪽부터 맞추고, 각 쌍이 같거나 한쪽이 1이어야 한다. 첫 preset이 가장 흔한 조용한 버그다. 에러 없이 N×N 행렬을 만든다.

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 jj by the sum of row jj. (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.

NumPy Linear maps, dot products and norms
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)")
 
NumPy Shapes: attention, GQA and MoE with einsum; broadcasting bugs
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)
 
확인 문제Check yourself

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 (b,h,t,s,d)(b,h,t,s,d) costs one multiply-add, so FLOPs =2⋅BHTSD=2⋅4⋅32⋅20482⋅128≈2.75×1011= 2\cdot B H T S D = 2\cdot4\cdot32\cdot2048^2\cdot128 \approx 2.75\times10^{11}. The T⋅ST\cdot S factor is the quadratic cost of attention; the output alone, BHTSB H T S scores, is about 0.5 G elements (1 GB in bf16), which is why FlashAttention never materialises it.

확인 문제Check yourself

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?

max⁡∥d∥∞≤1g⊤d\max_{\|d\|_\infty \le 1} g^\top d is attained at the corner d=sign⁡(g)d = \operatorname{sign}(g) with value ∥g∥1\|g\|_1 (the dual of ℓ∞\ell_\infty is ℓ1\ell_1). With ℓ2\ell_2 it would be g/∥g∥2g/\|g\|_2; with ℓ1\ell_1 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.
  • a⊤b=∥a∥∥b∥cos⁡θa^\top b = \|a\|\|b\|\cos\theta; random dot products scale like d\sqrt d, hence 1/d1/\sqrt d in attention.
  • Norms are rulers. The steepest direction depends on the ruler: ℓ2→g/∥g∥\ell_2 \to g/\|g\|, ℓ∞→sign⁡(g)\ell_\infty \to \operatorname{sign}(g); for matrices, Frobenius vs spectral.
  • ∥A∥2\|A\|_2 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 =2∏nℓ=2\prod n_\ell. Broadcast from the right, and watch (N,) vs (N,1).

Where this is used

조용한 오류의 대부분은 세 가지 shape 버그에서 나온다. (1) (N,)에서 (N,1)을 빼면 모든 쌍의 차이로 된 N×N 행렬이 나온다. 이렇게 계산한 회귀 손실은 틀렸지만 잘 돌아간다. (2) keepdims=True 없이 정규화하기. (B,T,V) logit에서 p / p.sum(-1)은 (B,T) 배열로 나누게 되어 대개 에러가 나지만, 정사각 (T,T) attention 행렬에서는 그대로 돌아가면서 열 jj를 행 jj의 합으로 나눈다. (3) (B,) 꼴의 sequence 단위 값은 token 단위 log-prob (B,T)에 곱하기 전에 (B,1)이 되어야 한다. GRPO의 sequence 단위 advantage가 정확히 이 경우다.

직접 구현하기

첫 블록은 위의 항등식을 모두 수치로 확인하고, 두 번째 블록은 multi-head attention, GQA, MoE 결합을 einsum으로 쓰고 broadcasting 버그를 재현한다.

NumPy 선형 사상, 내적, 노름
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를 넘지 않는다)")
 
NumPy Shape: einsum으로 쓴 attention, GQA, MoE와 broadcasting 버그
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)
 
확인 문제Check yourself

query의 shape이 (B=4, H=32, T=2048, D=128), key가 (4, 32, 2048, 128)이다. einsum('bhtd,bhsd->bhts', q, k)의 비용은?

다섯 index (b,h,t,s,d)(b,h,t,s,d)의 모든 조합마다 곱셈-덧셈이 한 번이므로 FLOPs =2⋅BHTSD=2⋅4⋅32⋅20482⋅128≈2.75×1011= 2\cdot B H T S D = 2\cdot4\cdot32\cdot2048^2\cdot128 \approx 2.75\times10^{11}. T⋅ST\cdot S 인자가 attention의 이차 비용이다. 출력만 해도 점수 BHTSB H T S개, 약 0.5 G 원소(bf16으로 1 GB)라서 FlashAttention은 이것을 메모리에 만들지 않는다.

확인 문제Check yourself

step d를 어떤 노름으로 잴 때 최급강하 방향이 −sign(g), 즉 이동평균을 끈 Adam의 방향이 되는가?

max⁡∥d∥∞≤1g⊤d\max_{\|d\|_\infty \le 1} g^\top d는 모서리 d=sign⁡(g)d = \operatorname{sign}(g)에서 값 ∥g∥1\|g\|_1로 달성된다(ℓ∞\ell_\infty의 쌍대는 ℓ1\ell_1). ℓ2\ell_2라면 g/∥g∥2g/\|g\|_2, ℓ1\ell_1이라면 가장 큰 좌표 하나만 움직인다.

정리

  • 행렬은 기저 벡터의 상을 열로 갖는 선형 사상이다. 곱은 합성이고, 결합법칙은 성립하지만 교환법칙은 아니며, 괄호 위치가 비용을 바꾼다.
  • a⊤b=∥a∥∥b∥cos⁡θa^\top b = \|a\|\|b\|\cos\theta. 무작위 내적은 d\sqrt d로 커지므로 attention에 1/d1/\sqrt d가 들어간다.
  • 노름은 자다. 최급 방향은 자에 따라 다르다. ℓ2→g/∥g∥\ell_2 \to g/\|g\|, ℓ∞→sign⁡(g)\ell_\infty \to \operatorname{sign}(g). 행렬에서는 Frobenius 대 spectral.
  • ∥A∥2\|A\|_2는 최대 늘임 배율이고 곱에 대해 부등식을 만족하므로, layer들의 곱이 신호를 얼마나 키울 수 있는지 묶어 준다.
  • 텐서 식은 einsum으로 읽는다. 합해지는 글자, batch 글자, 비용 =2∏nℓ=2\prod n_\ell. broadcasting은 오른쪽부터, 그리고 (N,) 대 (N,1)을 조심한다.

이 사이트에서 쓰이는 곳

더 읽을거리Further reading