---
title: "LLM 수학 01 — 선형대수와 tensor shape"
slug: "llm-math-01-linear-algebra"
category: "AI / LLM"
topic: "ai-llm"
subtopic: "mathematics"
tags: ["Linear Algebra","Tensor","Embedding","Attention","LoRA"]
status: "published"
created: "2026-07-21"
updated: "2026-07-21"
summary: "vector와 matrix의 연산을 embedding, attention, cosine similarity, SVD와 LoRA에 연결하고 모든 계산을 tensor shape로 검증한다."
kind: "Study Note"
evidence: "원 논문·공식 유도·손계산"
series: "공식에서 시스템까지 이어지는 LLM 수학"
---

[전체 지도](/posts/llm-math-00-roadmap) 다음에 선형대수를 먼저 둔 이유는 LLM 코드의 대부분이 숫자 배열의 모양을 바꾸고 곱하는 과정이기 때문이다. 추상적인 vector space 이론을 전부 배우기 전에, 식이 허용하는 shape와 각 축의 의미부터 잡는다.

## 네 종류의 숫자 배열

### Scalar

scalar는 숫자 하나다.

$$
a\in\mathbb{R}
$$

learning rate $\eta$, loss $L$, temperature $\tau$가 scalar다.

### Vector

vector는 순서가 있는 숫자 목록이다.

$$
\mathbf{x}=
\begin{bmatrix}
2\\-1\\3
\end{bmatrix}
\in\mathbb{R}^{3}
$$

token embedding 하나를 길이 $D$인 vector로 본다. vector의 방향은 column으로 쓰지만, 실제 tensor library에서는 shape `(D,)`일 수 있다. 논문 표기와 memory layout을 같은 것으로 보면 안 된다.

### Matrix

matrix는 row와 column을 가진다.

$$
X=
\begin{bmatrix}
1&0&2\\
-1&3&1
\end{bmatrix}
\in\mathbb{R}^{2\times3}
$$

sequence의 token representation을 쌓으면 보통 $X\in\mathbb{R}^{T\times D}$다. row $T$개는 token position, column $D$개는 feature다.

### Tensor

이 글에서는 3차원 이상 배열을 tensor라고 부른다. 엄밀한 수학의 tensor 정의보다 machine learning library의 용례에 맞춘다.

$$
X\in\mathbb{R}^{B\times T\times D}
$$

- $B$ — batch 안의 sequence 수
- $T$ — sequence당 token 수
- $D$ — token당 feature 수

multi-head로 나누면 $(B,T,D)$가 $(B,H,T,d_h)$로 바뀌고 보통 $D=H d_h$다. 축 이름을 쓰지 않으면 같은 숫자 8도 head 수인지 head dimension인지 알 수 없다.

## Index와 axis

$X_{ij}$는 matrix의 $i$번째 row, $j$번째 column 원소다. Python이 0부터 시작해도 수학식은 보통 1부터 시작한다.

$$
X=
\begin{bmatrix}
1&2&3\\
4&5&6
\end{bmatrix}
$$

- $X_{2,3}=6$
- $X_{2,\ast}=[4,5,6]$
- $X_{\ast,2}=[2,5]^\top$

softmax의 `dim=-1`은 마지막 axis를 따라 합이 1이 되게 만든다는 뜻이다. attention score가 $(B,H,T_q,T_k)$라면 마지막 $T_k$ axis에 softmax를 적용해야 각 query가 key 전체에 주는 weight 합이 1이 된다.

## Vector 덧셈과 scalar 곱

같은 차원의 vector끼리 원소별로 더한다.

$$
\begin{bmatrix}1\\2\end{bmatrix}
+
\begin{bmatrix}3\\-1\end{bmatrix}
=
\begin{bmatrix}4\\1\end{bmatrix}
$$

scalar 곱은 vector의 크기를 바꾸고 음수라면 방향도 뒤집는다.

$$
2\begin{bmatrix}1\\-3\end{bmatrix}
=
\begin{bmatrix}2\\-6\end{bmatrix}
$$

embedding에 position vector를 더하는 것은 같은 $D$차원 공간에서 두 signal을 원소별로 합하는 일이다.

$$
h_t=e_{\text{token},t}+e_{\text{position},t}
$$

두 vector의 길이가 다르면 이 덧셈은 정의되지 않는다.

## 세 가지 곱을 구분한다

### Element-wise product

Hadamard product는 같은 위치의 원소끼리 곱한다.

$$
\mathbf{x}\odot\mathbf{y}
=
\begin{bmatrix}x_1y_1\\x_2y_2\end{bmatrix}
$$

shape는 그대로다. gating에서 자주 본다.

$$
\operatorname{gate}(x)=\sigma(W_gx)\odot (W_vx)
$$

### Dot product

두 vector의 내적은 같은 위치의 곱을 더한 scalar다.

$$
\mathbf{x}\cdot\mathbf{y}
=
\mathbf{x}^{\top}\mathbf{y}
=
\sum_{i=1}^{D}x_i y_i
$$

$x=[1,2]$, $y=[3,-1]$이면

$$
x\cdot y=1\cdot3+2\cdot(-1)=1
$$

내적은 두 vector가 얼마나 같은 방향을 향하는지와 각 vector의 크기를 함께 반영한다. attention score와 dense retrieval score에 자주 사용한다.

### Outer product

column vector와 row vector를 곱하면 matrix가 된다.

$$
\mathbf{x}\mathbf{y}^{\top}
\in\mathbb{R}^{m\times n}
$$

$$
\begin{bmatrix}1\\2\end{bmatrix}
\begin{bmatrix}3&4&5\end{bmatrix}
=
\begin{bmatrix}
3&4&5\\
6&8&10
\end{bmatrix}
$$

low-rank update와 covariance를 볼 때 중요하다.

## Matrix multiplication

$A\in\mathbb{R}^{m\times n}$와 $B\in\mathbb{R}^{n\times p}$만 곱할 수 있다. 가운데 차원 $n$이 같아야 하고 결과는 $(m,p)$다.

$$
C=AB,\qquad C_{ij}=\sum_{k=1}^{n}A_{ik}B_{kj}
$$

$$
\underbrace{(m,n)}_{A}
\underbrace{(n,p)}_{B}
\rightarrow
\underbrace{(m,p)}_{C}
$$

예를 들어 token representation $X\in\mathbb{R}^{T\times D}$에 weight $W\in\mathbb{R}^{D\times d}$를 곱하면 token 수는 유지되고 feature 차원만 $d$로 바뀐다.

$$
XW\in\mathbb{R}^{T\times d}
$$

linear layer의 핵심이다.

$$
y=xW+b
$$

bias $b\in\mathbb{R}^{d}$는 모든 token row에 broadcasting되어 더해진다. broadcasting은 수학적으로 자동인 규칙이 아니라 library가 같은 $b$를 여러 row에 적용하는 구현 규칙이다.

## Transpose

transpose는 row와 column을 바꾼다.

$$
A\in\mathbb{R}^{m\times n}
\Rightarrow
A^\top\in\mathbb{R}^{n\times m}
$$

$Q,K\in\mathbb{R}^{T\times d_k}$일 때 $QK$는 정의되지 않지만 $QK^\top$는 가능하다.

$$
(T,d_k)(d_k,T)=(T,T)
$$

결과의 $(i,j)$ 원소는 query token $i$와 key token $j$의 dot product다.

$$
(QK^\top)_{ij}=q_i\cdot k_j
$$

transpose가 단순히 “모양을 맞추는 기호”가 아니라 모든 query-key 쌍의 내적을 한 번에 계산하게 한다.

## Norm과 거리

### L1 norm

$$
\lVert x\rVert_1=\sum_i|x_i|
$$

큰 원소의 수를 줄이는 sparse regularization과 연결된다.

### L2 norm

$$
\lVert x\rVert_2=\sqrt{\sum_i x_i^2}
$$

$x=[3,4]$이면 $\lVert x\rVert_2=5$다.

unit normalization은 방향을 유지하고 길이를 1로 만든다.

$$
\hat{x}=\frac{x}{\lVert x\rVert_2}
$$

### Euclidean distance

$$
d(x,y)=\lVert x-y\rVert_2
$$

가까울수록 작은 값이 좋은 distance다. similarity는 보통 클수록 좋다. vector database 설정에서 distance와 similarity의 정렬 방향을 확인해야 한다.

## Cosine similarity와 dot product

cosine similarity는 vector의 각도만 비교한다.

$$
\cos(x,y)=\frac{x\cdot y}{\lVert x\rVert_2\lVert y\rVert_2}
$$

$x=[1,0]$, $y=[3,0]$이면 cosine은 1이지만 dot product는 3이다. 방향은 같고 길이는 다르다.

두 vector를 모두 L2-normalize했다면

$$
\hat{x}\cdot\hat{y}=\cos(x,y)
$$

따라서 normalized embedding에서는 dot product 검색과 cosine 검색이 같은 ranking을 만든다. normalize하지 않았다면 embedding norm이 score에 들어간다.

unit vector에서는 squared Euclidean distance도 cosine과 단조 관계다.

$$
\lVert\hat{x}-\hat{y}\rVert_2^2
=2-2\cos(x,y)
$$

이 관계는 “어떤 metric을 써도 같다”가 아니라 양쪽 vector가 unit-normalized됐다는 조건 아래에서만 성립한다.

## Linear combination과 span

vector의 linear combination은 scalar를 곱해 더한 것이다.

$$
y=a_1v_1+\cdots+a_kv_k
$$

attention output도 value vector의 linear combination이다.

$$
o_i=\sum_j\alpha_{ij}v_j,qquad \alpha_{ij}\ge0,\quad\sum_j\alpha_{ij}=1
$$

softmax weight이므로 단순 linear combination보다 강한 조건을 갖는다. weight가 음수가 아니고 합이 1인 convex combination이다. 단, 뒤의 output projection과 residual까지 포함한 전체 block 출력이 value의 convex combination이라는 뜻은 아니다.

주어진 vector들의 모든 linear combination 집합을 span이라고 한다. embedding space의 한 점을 “특정 feature vector 몇 개의 조합”으로 해석하는 논문에서 등장한다.

## Linear independence, basis, dimension

vector 집합이 linearly independent라는 것은

$$
a_1v_1+\cdots+a_kv_k=0
$$

을 만족하는 유일한 계수가 모두 0이라는 뜻이다. 다른 vector의 조합으로 만들 수 없는 방향들이다.

basis는 공간을 span하면서 서로 independent인 vector 집합이다. $\mathbb{R}^D$의 standard basis는 각 축 하나만 1인 $D$개 vector다.

model dimension $D=4096$은 4096개의 사람이 이름 붙인 의미 축을 뜻하지 않는다. 학습된 representation은 basis를 회전해도 후속 weight가 같이 바뀌면 같은 함수를 표현할 수 있다. 한 coordinate를 곧바로 하나의 인간 개념이라고 읽는 것은 근거가 부족하다.

## Rank

matrix rank는 independent한 row 또는 column의 최대 개수다.

$$
\operatorname{rank}(A)\le\min(m,n)
$$

$$
A=
\begin{bmatrix}
1&2\\
2&4
\end{bmatrix}
$$

두 번째 row가 첫 번째 row의 2배이므로 rank는 1이다. matrix가 2차원 입력을 받아도 출력 변화가 사실상 한 방향에만 놓인다.

rank가 작다는 것은 matrix의 모든 원소가 작다는 뜻이 아니다. 표현 가능한 독립 방향 수가 적다는 뜻이다.

## Inverse와 determinant는 어디까지 필요한가

square matrix $A$에 대해 $A^{-1}$가 존재하면

$$
A^{-1}A=I
$$

이다. determinant가 0이면 inverse가 없고 column들이 linearly dependent하다.

LLM의 forward pass에서 큰 weight inverse를 직접 구하는 일은 드물다. 하지만 다음 맥락을 읽는 데 개념이 필요하다.

- least squares와 linear regression의 해
- covariance matrix와 whitening
- second-order optimization의 Hessian inverse 근사
- 특정 transformation이 정보를 잃는지 보는 invertibility

실제 계산은 inverse를 명시적으로 구하기보다 안정적인 linear solve나 factorization을 쓴다.

## Eigenvalue와 eigenvector

square matrix $A$가 어떤 vector $v$의 방향은 바꾸지 않고 크기만 $\lambda$배 한다면

$$
Av=\lambda v
$$

이고 $v$는 eigenvector, $\lambda$는 eigenvalue다.

직관적으로 transformation이 가진 고유 방향과 그 방향의 확대율이다. covariance의 principal direction, optimization의 curvature, training stability 분석에서 등장한다.

모든 matrix가 real eigenvalue와 충분한 eigenvector를 가지는 것은 아니다. “weight의 eigenvalue”라는 표현을 보면 matrix 조건과 어떤 operator를 분석하는지 확인한다.

## Singular Value Decomposition

SVD는 rectangular matrix에도 적용된다.

$$
A=U\Sigma V^\top
$$

- $V^\top$ — 입력을 새로운 orthogonal basis로 본다.
- $\Sigma$ — 각 방향을 singular value만큼 늘리거나 줄인다.
- $U$ — 출력 공간의 basis로 옮긴다.

singular value가 큰 방향부터 $r$개만 남기면 best rank-$r$ approximation을 얻는다. 여기서 “best”는 Frobenius norm 또는 spectral norm 기준이라는 조건이 붙는다.

$$
A_r=U_r\Sigma_rV_r^\top
$$

모든 low-rank 학습법이 기존 weight의 truncated SVD를 그대로 사용한다는 뜻은 아니다. LoRA는 update가 low rank라고 가정하고 두 matrix를 직접 학습한다.

## LoRA의 shape와 parameter 수

원래 weight가 $W_0\in\mathbb{R}^{d_{out}\times d_{in}}$라면 LoRA는 frozen weight에 low-rank update를 더한다.

$$
W=W_0+\Delta W,qquad \Delta W=BA
$$

$$
B\in\mathbb{R}^{d_{out}\times r},\qquad
A\in\mathbb{R}^{r\times d_{in}}
$$

원래 full update parameter 수는

$$
d_{out}d_{in}
$$

이고 LoRA parameter 수는

$$
r(d_{out}+d_{in})
$$

이다. $d_{in}=d_{out}=4096$, $r=8$이면

$$
\frac{8(4096+4096)}{4096^2}
=\frac{65{,}536}{16{,}777{,}216}
\approx0.00390625
$$

해당 matrix에 대해 full weight의 약 0.39%를 학습한다. model 전체 비율은 LoRA를 어느 module에 붙였는지에 따라 달라진다.

## Embedding lookup은 matrix row 선택이다

vocabulary size가 $V$, model dimension이 $D$이면 embedding table은

$$
E\in\mathbb{R}^{V\times D}
$$

이다. token id $i$의 embedding은 $E$의 $i$번째 row다.

one-hot vector $e_i\in\mathbb{R}^{V}$를 쓴다면

$$
e_i^\top E=E_{i,\ast}
$$

이므로 embedding lookup을 one-hot과 matrix multiplication으로 이해할 수 있다. 구현은 거대한 one-hot을 만들지 않고 row를 바로 찾는다.

## Attention을 shape만으로 검증한다

batch를 잠시 빼고

$$
X\in\mathbb{R}^{T\times D}
$$

에서 시작한다.

$$
W_Q,W_K\in\mathbb{R}^{D\times d_k},\qquad
W_V\in\mathbb{R}^{D\times d_v}
$$

$$
Q=XW_Q\in\mathbb{R}^{T\times d_k}
$$

$$
K=XW_K\in\mathbb{R}^{T\times d_k}
$$

$$
V=XW_V\in\mathbb{R}^{T\times d_v}
$$

score matrix는

$$
S=\frac{QK^\top}{\sqrt{d_k}}
\in\mathbb{R}^{T\times T}
$$

row-wise softmax 뒤에도 shape는 $(T,T)$다.

$$
P=\operatorname{softmax}(S)
$$

마지막으로

$$
O=PV\in\mathbb{R}^{T\times d_v}
$$

다. $P$의 각 row가 $V$의 row들을 섞는다. “attention이 token을 섞고 linear layer가 feature를 섞는다”는 설명을 shape로 확인할 수 있다.

## Multi-head shape

$D=H d_h$라고 하자.

```text
입력 X                 (B, T, D)
Q, K, V projection     (B, T, H × d_h)
head 축 분리            (B, H, T, d_h)
QKᵀ                    (B, H, T, T)
softmax × V            (B, H, T, d_h)
head 결합               (B, T, D)
output projection      (B, T, D)
```

`transpose(1, 2)`가 자주 등장하는 이유는 $(B,T,H,d_h)$를 $(B,H,T,d_h)$로 바꿔 head별 matrix multiplication이 가능하게 하기 위해서다. transpose 뒤 tensor가 contiguous하지 않을 수 있다는 것은 수학이 아니라 memory layout 문제다.

## Batch matrix multiplication

$(B,H,T,d_h)$ tensor끼리 attention score를 계산할 때 앞의 $B,H$ 축을 batch dimension처럼 유지하고 마지막 두 축만 matrix multiply한다.

$$
(B,H,T,d_h)\ @\ (B,H,d_h,T)
\rightarrow(B,H,T,T)
$$

수학식이 $QK^\top$ 한 줄이어도 실제 구현에는 batch와 head 축이 숨어 있다.

## Einstein notation을 읽는 법

Einstein summation은 반복 index를 합한다. attention score를

$$
S_{bhij}=\sum_d Q_{bhid}K_{bhjd}
$$

로 쓰면 의미가 선명해진다.

- $b$ — batch, 유지
- $h$ — head, 유지
- $i$ — query position, 유지
- $j$ — key position, 유지
- $d$ — head feature, 합으로 사라짐

코드의 `einsum("bhid,bhjd->bhij", Q, K)`가 이 식이다. einsum 문자열을 외우기보다 어떤 axis가 결과에 남고 어떤 axis가 합쳐지는지 읽는다.

## Parameter 수와 matrix shape

bias를 제외한 linear layer의 parameter 수는 input dimension과 output dimension의 곱이다.

$$
W\in\mathbb{R}^{d_{out}\times d_{in}}
\Rightarrow \#W=d_{out}d_{in}
$$

Transformer block에서 Q, K, V, output projection이 모두 $D\times D$라면 attention projection만 대략 $4D^2$ parameter다. FFN hidden dimension이 $D_{ff}$면 두 linear layer는 약 $2DD_{ff}$다.

parameter 수와 activation memory는 다르다. parameter는 model 크기에 따라, activation은 batch와 sequence length에도 따라 커진다.

## 자주 생기는 오해

### Matrix multiplication은 element-wise product가 아니다

`A * B`가 library마다 scalar 곱 또는 element-wise 곱일 수 있다. 논문의 $AB$는 보통 matrix multiplication이다. API operator 의미를 확인한다.

### 높은 cosine은 인과관계가 아니다

embedding 방향이 비슷하다는 것은 model이 학습한 representation과 metric에서 가깝다는 뜻이다. 두 문장이 사실이라는 보장이나 한 문장이 다른 문장의 원인이라는 뜻은 아니다.

### 차원이 크면 무조건 표현력이 좋지는 않다

큰 $D$는 capacity와 비용을 함께 늘린다. 데이터, optimization, architecture가 그 차원을 유용하게 쓰는지 별도 문제다.

### Rank와 embedding dimension은 다르다

matrix shape가 $(4096,4096)$여도 rank가 4096일 필요는 없다. 반대로 LoRA rank 8은 전체 model representation이 8차원이라는 뜻이 아니라 update matrix의 rank upper bound가 8이라는 뜻이다.

## 손계산

두 token representation을 다음처럼 둔다.

$$
X=
\begin{bmatrix}
1&0\\
1&1
\end{bmatrix},\quad
W_Q=I,\quad
W_K=
\begin{bmatrix}
1&0\\
0&2
\end{bmatrix}
$$

그러면

$$
Q=X=
\begin{bmatrix}
1&0\\
1&1
\end{bmatrix}
$$

$$
K=XW_K=
\begin{bmatrix}
1&0\\
1&2
\end{bmatrix}
$$

$$
QK^\top=
\begin{bmatrix}
1&1\\
1&3
\end{bmatrix}
$$

각 원소를 직접 dot product로 확인한다.

- $(1,1)$ — $[1,0]\cdot[1,0]=1$
- $(1,2)$ — $[1,0]\cdot[1,2]=1$
- $(2,1)$ — $[1,1]\cdot[1,0]=1$
- $(2,2)$ — $[1,1]\cdot[1,2]=3$

여기까지는 score다. $\sqrt{2}$로 나누고 row-wise softmax한 뒤 $V$를 곱해야 attention output이 된다.

## 완료 체크

- [ ] $(m,n)(n,p)=(m,p)$를 바로 확인한다.
- [ ] dot, outer, element-wise product의 출력 shape를 구분한다.
- [ ] norm, distance, similarity의 정렬 방향을 구분한다.
- [ ] normalized vector에서 cosine과 dot product가 같음을 유도한다.
- [ ] $QK^\top$의 각 row와 column 의미를 설명한다.
- [ ] multi-head attention의 $(B,H,T,T)$ 축을 설명한다.
- [ ] rank-$r$ LoRA update의 두 matrix shape와 parameter 수를 계산한다.
- [ ] eigen decomposition과 SVD의 적용 대상 차이를 말한다.

다음 글은 이 vector들이 probability distribution으로 바뀌고 loss가 되는 과정을 다룬다. [LLM 수학 02 — 확률과 정보이론](/posts/llm-math-02-probability-information).

## Reference

- Gilbert Strang. [Introduction to Linear Algebra](https://math.mit.edu/~gs/linearalgebra/), Wellesley-Cambridge Press.
- Ian Goodfellow, Yoshua Bengio, Aaron Courville. [Deep Learning, Linear Algebra](https://www.deeplearningbook.org/contents/linear_algebra.html), 2016.
- Ashish Vaswani 외. [Attention Is All You Need](https://arxiv.org/abs/1706.03762), section 3.2.
- Edward J. Hu 외. [LoRA](https://arxiv.org/abs/2106.09685), 2021.
