Statistical
Deep Learning
Likelihood에서 출발해 Diffusion까지, 수학·통계 전공자를 위한 Deep Learning
이 책은 2025년에 진행한 Deep Learning 강의(15주)를 주제별로 재구성하고, 수학·통계 전공자가 읽을 수 있는 수준으로 다시 쓴 교재이다. 강의 슬라이드가 그림과 직관 위주였다면, 이 책은 각 개념을 definition, derivation, proof의 형태로 정리한다.
책 전체를 관통하는 관점은 하나다. Deep learning model은 parameter $\theta$를 가진 거대한 statistical model이고, training은 결국 estimation이다. Loss function은 likelihood에서 나오고, generative model은 $p_\theta(x)$를 maximize하는 문제이며, 그 과정에서 등장하는 KL divergence, ELBO, score function은 모두 통계학의 언어로 설명된다.
Prerequisites. Linear algebra(행렬 곱, rank, eigenvalue), multivariable calculus(gradient, Jacobian, chain rule), mathematical statistics(random variable, expectation, MLE, conditional distribution) 수준을 가정한다. Measure theory는 필요하지 않다.
Language convention. 본문은 한국어로 쓰고, 모든 technical term은 영어 그대로 쓴다. 번역어가 정착되지 않은 용어가 많고, 논문과 코드에서 마주치는 형태 그대로 익히는 편이 실용적이기 때문이다.
Notation. Scalar는 $x$, vector는 $\bx$, matrix는 $\bW$로 쓰되, 문맥상 분명하면 굵은 글씨를 생략한다. Vector는 기본적으로 column vector이다. $p_{\text{data}}$는 실제 data distribution, $p_\theta$는 model distribution, $\hat p$는 empirical distribution을 뜻한다. $\log$는 natural log이다. 전체 기호표와 핵심 공식 모음은 Appendix B에 있다.
구성. Part I은 estimation에서 출발해 neural network, loss, optimization을 통계학의 언어로 세우고, 큰 model이 왜 일반화하는지(Chapter 5)로 마무리한다. Part II는 data의 구조에 맞춘 architecture(CNN, RNN, Transformer, ViT)와 긴 sequence를 위한 효율적 attention과 state space model, 그리고 GNN을 다룬다. Part III는 label 없이 배우고 옮겨 쓰는 representation, 그 해석, 그리고 label이 적거나 틀렸거나 치우친 data를 다루는 방법이다. Part IV는 VAE, GAN, score-based model, diffusion, normalizing flow를 거쳐 SDE와 flow matching으로 통합되는 generative model의 흐름이다. Part V는 예측의 불확실성, 성능 평가, distribution shift를 통계적으로 다룬다. Part VI는 survival analysis, reinforcement learning, large language model, vision-language model로의 확장이고, Part VII는 분산 학습, parameter-efficient fine-tuning과 quantization, routing과 mixture of experts처럼 큰 model을 학습하고 배포하는 방법을 다룬다. Part I을 먼저 읽고 나머지는 관심에 따라 골라 읽어도 되지만, Part IV는 Chapter 15부터 순서대로 읽기를 권한다. Chapter 5, 10, 11, 14, 19–23, 25, 27–30은 강의 범위 밖에서 새로 추가한 장이다. 부록에는 PyTorch 실습(A), 기호와 공식(B), 참고문헌(C), 용어 색인(D)이 있다.
Foundations
Chapter 1Estimation과 Statistical Learning
Lecture Week 01 (Part 1)
Deep learning을 statistical model로 읽기 위한 출발점을 정리한다. Random variable과 distribution, estimator의 성질, maximum likelihood estimation(MLE)과 MAP, 그리고 linear·logistic regression을 다시 살펴본다. 이 장의 모든 개념은 이후 loss function(Chapter 3), regularization(Chapter 4), generative model(Part IV)에서 다시 쓰인다.
1.1Deterministic model과 Stochastic model
현상을 기술하는 model은 크게 두 종류로 나눌 수 있다. Deterministic model은 input이 정해지면 output이 하나로 정해진다. Randomness가 없으므로 "얼마나 맞을 확률이 높은가"라는 개념 자체가 존재하지 않는다. 반면 stochastic (probabilistic) model은 randomness와 uncertainty를 model 안에 포함한다. Linear regression $$y = \beta_0 + \beta_1 x + \epsilon,\qquad \epsilon\sim\N(0,\sigma^2)$$ 에서 $\epsilon$ 항이 바로 그 randomness이고, 이 때문에 같은 $x$에 대해서도 $y$는 distribution $\N(\beta_0+\beta_1x,\sigma^2)$을 가진다.
Deep learning model은 겉으로 보면 $y=f_\theta(x)$라는 deterministic function이지만, 학습의 근거가 되는 loss function은 모두 stochastic model에서 유도된다. Network의 output을 어떤 distribution의 parameter로 해석하는 순간 deterministic function이 stochastic model이 된다. 이 관점은 Chapter 3에서 구체화된다.
1.2Random variable과 Distribution
Random experiment의 가능한 모든 outcome의 집합을 sample space $\Omega$라 한다. Random variable $X$는 sample space에서 real number로 가는 function $X:\Omega\to\R$이다. 즉 random variable의 domain은 sample space이다.
Random variable은 "변수"라는 이름과 달리 function이라는 점이 핵심이다. 동전 두 개를 동시에 던지는 실험에서 $\Omega=\{HH,HT,TH,TT\}$이고, $X$를 "앞면의 개수"로 정의하면 $X(HH)=2,\ X(HT)=X(TH)=1,\ X(TT)=0$이다.
| Outcome $\omega$ | $X(\omega)$ | $P(X=x)$ |
|---|---|---|
| HH | 2 | 1/4 |
| HT, TH | 1 | 1/2 |
| TT | 0 | 1/4 |
이 표는 $X$의 값과 그 확률을 대응시키는 function, 즉 probability mass function(pmf) $f_X(x)=P(X=x)$ 그 자체이다. 표도 function이다. 정의역의 각 원소에 값 하나를 대응시키기 때문이다. Continuous random variable에서는 probability density function(pdf) $f_X$가 같은 역할을 하며, $P(a\le X\le b)=\int_a^bf_X(x)\,\dd x$이다. 예를 들어 $X\sim\N(\mu,\sigma^2)$이면 $$f_X(x) = \frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^2\right\}.$$ 여기서 $\mu,\sigma^2$처럼 distribution의 모양을 결정하는 상수를 parameter라 하고, parameter를 명시해 $f(x;\theta)$ 또는 $f_\theta(x)$로 쓴다. Parameter로 index된 distribution의 모임 $\{f(\cdot\,;\theta):\theta\in\Theta\}$을 parametric family 또는 statistical model이라 한다.
이후 자주 쓰는 기본 개념을 정리해 둔다. Expectation $\E[g(X)]=\int g(x)f_X(x)\,\dd x$, variance $\Var(X)=\E[(X-\E X)^2]$, 두 변수의 joint density $f_{X,Y}$에서 conditional density $f_{Y\mid X}(y\mid x)=f_{X,Y}(x,y)/f_X(x)$, 그리고 Bayes rule $f_{X\mid Y}(x\mid y)=f_{Y\mid X}(y\mid x)f_X(x)/f_Y(y)$이다.
1.3Estimation과 estimator의 성질
통계학의 기본 상황은 다음과 같다. 관심 대상인 population은 distribution $f(x;\theta)$를 따르지만 $\theta$는 모른다. 우리가 가진 것은 population에서 뽑은 sample $X_1,\dots,X_n$뿐이다. 실제 정답 population이 있고, 그것을 sample data로 추측하는 것이 estimation이다.
Sample의 function $\hat\theta = T(X_1,\dots,X_n)$을 $\theta$의 estimator라 하고, 관측값을 대입한 값 $T(x_1,\dots,x_n)$을 estimate라 한다. Estimator는 random variable의 function이므로 그 자체로 random variable이며, 고유한 distribution(sampling distribution)을 가진다.
Estimator가 random variable이라는 사실이 통계적 inference의 근거다. Sample mean $\bar X=\frac1n\sum X_i$는 매번 다른 sample에서 다른 값을 가지므로 분산이 있고, 그 분산을 알면 confidence interval과 p-value를 계산할 수 있다. Estimator의 좋고 나쁨은 다음 기준으로 판단한다.
(a) $\mathrm{Bias}(\hat\theta)=\E[\hat\theta]-\theta$. Bias가 0이면 unbiased이다.
(b) $\mathrm{MSE}(\hat\theta)=\E\big[(\hat\theta-\theta)^2\big]$.
(c) $n\to\infty$일 때 $\hat\theta_n\xrightarrow{p}\theta$이면 consistent이다.
$$\mathrm{MSE}(\hat\theta)=\Var(\hat\theta)+\mathrm{Bias}(\hat\theta)^2.$$
$\hat\theta-\theta=(\hat\theta-\E\hat\theta)+(\E\hat\theta-\theta)$를 제곱하고 expectation을 취하면, cross term $2(\E\hat\theta-\theta)\E[\hat\theta-\E\hat\theta]=0$이므로 남는 것은 $\Var(\hat\theta)+\mathrm{Bias}^2$이다.
Unbiased라고 항상 좋은 것은 아니다. Bias를 조금 허용하고 variance를 크게 줄이면 MSE가 작아질 수 있다. Ridge regression, weight decay, data augmentation 같은 regularization(Chapter 4)이 모두 이 trade-off를 이용한다. Model의 inductive bias와 data 양의 관계(Chapter 9)도 같은 관점으로 읽을 수 있다.
세 가지 setting에서 "무엇을 estimate하는가"를 비교하면 다음과 같다.
| Setting | Model | Estimate 대상 |
|---|---|---|
| Population mean | $X\sim\N(\mu,\sigma^2)$, $\sigma^2$ known | $\theta=\mu$ |
| Linear regression | $\by=\bX\bbeta+\beps$ | $\theta=\bbeta$, 즉 $X$와 $y$의 관계를 잘 설명하는 계수 |
| Deep learning | $y\mid x \sim p_\theta(y\mid x)$ | $\theta$ = 수백만~수십억 개의 weight |
Deep learning은 세 번째 줄에 해당한다. Parameter를 weight라 부르고, 그 수가 극단적으로 많다는 점만 다를 뿐 구조는 같다. 다만 목적이 다르다. Regression에서는 $\hat\beta$ 자체를 해석하고 검정하는 inference가 목적인 경우가 많다. $\hat\beta$가 random variable이므로 confidence interval과 p-value를 계산할 수 있다. Deep learning에서는 $\hat\theta$로 새 data의 $y$를 맞히는 prediction이 목적이며, 개별 weight의 값에는 관심이 없다.
1.4Maximum Likelihood Estimation
$X_1,\dots,X_n$이 joint density $f(x_1,\dots,x_n;\theta)$를 가질 때, 관측값 $x_1,\dots,x_n$을 고정하고 $\theta$의 function으로 본 $$\L(\theta) = f(x_1,\dots,x_n;\theta)$$ 를 likelihood function이라 한다. $X_i \iid f(\cdot\,;\theta)$이면 $\L(\theta)=\prod_{i=1}^n f(x_i;\theta)$이다.
Density와 likelihood는 같은 식이지만 무엇을 변수로 보느냐가 다르다. Density는 $\theta$를 고정하고 $x$의 function으로 보며 $x$에 대해 적분하면 1이다. Likelihood는 data를 고정하고 $\theta$의 function으로 보며, $\theta$에 대해 적분해도 1일 필요가 없다. 따라서 likelihood는 $\theta$의 probability distribution이 아니다. 강의 슬라이드처럼 이를 $f(\theta\mid x)$로 쓰면 Bayesian posterior와 혼동되므로, 이 책에서는 $\L(\theta)=f(\bx;\theta)$ 또는 $p(\bx\mid\theta)$로 쓴다.
$$\hat\theta_{\text{MLE}} = \argmax_\theta \L(\theta) = \argmax_\theta \sum_{i=1}^n \log f(x_i;\theta).$$ $\log$는 strictly increasing이므로 argmax를 바꾸지 않으며, product를 sum으로 바꿔 미분과 수치 계산을 모두 쉽게 한다. ($n$개의 확률을 곱하면 float의 범위를 쉽게 벗어난다.)
MLE의 직관은 "관측된 data가 나올 확률을 가장 크게 만드는 parameter를 고른다"는 것이다. 이때 distribution family(예: Gaussian)는 미리 정해져 있다고 가정한다. 미분 가능하면 보통 score equation $\nabla_\theta\log\L(\theta)=0$을 풀어 구한다.
$X_i\iid\text{Bernoulli}(p)$이고 $k=\sum x_i$라 하자. $\log\L(p)=k\log p+(n-k)\log(1-p)$이므로 $$\frac{\dd}{\dd p}\log\L(p) = \frac{k}{p}-\frac{n-k}{1-p}=0 \;\Longrightarrow\; \hat p = \frac{k}{n}.$$ Second derivative $-k/p^2-(n-k)/(1-p)^2 \lt 0$이므로 maximum이다. 동전을 10번 던져 앞면이 7번 나왔다면 $\hat p=0.7$이다.
$X_i\iid\N(\mu,\sigma^2)$이면 $$\log\L(\mu,\sigma^2)=-\frac n2\log(2\pi\sigma^2)-\frac{1}{2\sigma^2}\sum_{i=1}^n(x_i-\mu)^2.$$ $\partial_\mu=0$에서 $\hat\mu=\bar x$, $\partial_{\sigma^2}=-\frac{n}{2\sigma^2}+\frac{1}{2\sigma^4}\sum(x_i-\mu)^2=0$에서 $\hat\sigma^2=\frac1n\sum(x_i-\bar x)^2$이다. $\hat\mu$를 구할 때 $\sigma^2$의 값은 상관이 없다. 즉 Gaussian likelihood의 maximization은 squared error의 minimization과 같다. 이 사실은 regression과 deep learning에서 반복해서 등장한다. 한편 $\E[\hat\sigma^2]=\frac{n-1}{n}\sigma^2$이므로 MLE는 biased이고, $n-1$로 나눈 sample variance가 unbiased이다. MLE가 항상 unbiased인 것은 아니다.
MLE가 널리 쓰이는 이유는 좋은 asymptotic property를 갖기 때문이다.
$X_i\iid f(\cdot\,;\theta_0)$이고 regularity condition(identifiability, support가 $\theta$에 의존하지 않음, 3차 미분 가능성 등)이 성립하면
(a) Consistency: $\hat\theta_n \xrightarrow{p} \theta_0$.
(b) Asymptotic normality: $\sqrt n(\hat\theta_n-\theta_0)\xrightarrow{d}\N\big(0, I(\theta_0)^{-1}\big)$, 여기서
$$I(\theta)=\E_\theta\Big[\big(\partial_\theta\log f(X;\theta)\big)^2\Big]=-\E_\theta\big[\partial_\theta^2 \log f(X;\theta)\big]$$
는 sample 하나의 Fisher information이다.
(c) Invariance: $g$가 함수이면 $g(\theta)$의 MLE는 $g(\hat\theta)$이다.
(b)의 분산 $I(\theta_0)^{-1}/n$은 unbiased estimator가 가질 수 있는 분산의 하한(Cramér–Rao bound)과 같으므로, MLE는 asymptotically efficient하다. 증명의 핵심은 score equation을 $\theta_0$ 근처에서 Taylor 전개하는 것이다. $0=\ell'(\hat\theta)\approx\ell'(\theta_0)+(\hat\theta-\theta_0)\ell''(\theta_0)$에서 $\sqrt n(\hat\theta-\theta_0)\approx\frac{n^{-1/2}\ell'(\theta_0)}{-n^{-1}\ell''(\theta_0)}$이고, 분자는 CLT에 의해 $\N(0,I(\theta_0))$로, 분모는 LLN에 의해 $I(\theta_0)$로 수렴한다.
Deep learning에서는 이 정리의 가정이 대부분 깨진다. Parameter 수가 sample 수보다 많은 경우가 흔하고(parameter 수 고정이라는 가정 위반), 서로 다른 $\theta$가 같은 function을 표현한다(identifiability 위반: hidden unit의 순서를 바꾸거나 ReLU 앞뒤 weight를 $c$와 $1/c$로 scaling해도 같은 network). 그래서 deep learning에서는 $\hat\theta$의 distribution보다 held-out data에서의 prediction 성능으로 model을 평가한다. 그러나 loss function을 만드는 원리로서 MLE는 그대로 유효하다.
1.5Bayesian 관점과 MAP
Bayesian은 $\theta$ 자체를 random variable로 보고 prior distribution $p(\theta)$를 둔다. Data를 관측한 뒤의 믿음은 Bayes rule로 갱신한 posterior $$p(\theta\mid\bx)=\frac{p(\bx\mid\theta)\,p(\theta)}{p(\bx)}\propto\L(\theta)\,p(\theta)$$ 이다. Posterior를 최대화하는 값을 maximum a posteriori(MAP) estimate라 한다. $$\hat\theta_{\text{MAP}}=\argmax_\theta\big[\log\L(\theta)+\log p(\theta)\big].$$ Prior가 uniform(상수)이면 MAP는 MLE와 같다. Prior가 $\N(0,\tau^2\bI)$이면 $\log p(\theta)=-\|\theta\|^2/(2\tau^2)+C$이므로 MAP는 L2 penalty가 붙은 MLE가 된다. 이것이 deep learning의 weight decay이다(Chapter 4). 분모 $p(\bx)=\int p(\bx\mid\theta)p(\theta)\,\dd\theta$는 evidence(marginal likelihood)라 하는데, 이 적분이 계산 불가능하다는 문제는 Chapter 15의 VAE에서 다시 핵심이 된다.
1.6Hypothesis testing 요약
Statistical test는 관측된 차이가 실제 association인지 단순한 random fluctuation인지 판단하는 절차이다.
- Null hypothesis $H_0$: 검정하려는 주장. 보통 "effect가 없다", "차이가 없다".
- Alternative hypothesis $H_1$: 실제로 관심 있는 주장. Effect나 차이가 있다.
- Test statistic $T$: sample에서 계산하며 $H_0$에서 얼마나 벗어났는지를 측정한다($z$, $t$, $\chi^2$, $F$ 등). $H_0$ 하에서 $T$의 distribution을 알아야 한다.
- p-value: $H_0$가 참이라는 가정 하에서, 관측된 test statistic만큼 또는 그보다 더 극단적인 값이 나올 확률. 단측 검정이면 $P_{H_0}(T\ge t_{\text{obs}})$이다.
p-value는 "$H_0$가 참일 확률"이 아니다. Frequentist framework에서 $H_0$는 random event가 아니므로 그런 확률은 정의되지 않는다. p-value는 $H_0$를 가정했을 때 data가 얼마나 이례적인지를 나타낸다.
Theorem 1.9은 검정에 바로 쓰인다. $\hat\theta_j$의 standard error를 $\mathrm{SE}_j=\sqrt{[\hat I_n^{-1}]_{jj}}$($\hat I_n$은 observed information)로 추정하면, $H_0:\theta_j=0$에 대한 Wald statistic $z=\hat\theta_j/\mathrm{SE}_j$는 근사적으로 $\N(0,1)$을 따르고, 95% confidence interval은 $\hat\theta_j\pm1.96\,\mathrm{SE}_j$이다. Regression software가 출력하는 계수 표의 p-value가 이렇게 계산된다.
1.7Machine learning과 Data science
Computer program이 task $T$에 대해 performance measure $P$로 측정한 성능이 experience $E$를 통해 향상되면, 그 program은 $E$로부터 learn한다고 한다.
"기계가 생각할 수 있는가"라는 질문은 Turing(1950, "Computing Machinery and Intelligence")까지 거슬러 올라간다. Turing은 정의하기 어려운 이 질문을 "질문자가 대화만으로 기계와 사람을 구별할 수 있는가"라는 imitation game으로 바꿔 제시했다. Mitchell의 정의는 이를 측정 가능한 성능 향상의 문제로 다시 쓴 것이다.
Machine learning(ML)과 data science(DS)는 모두 data-driven이지만 목적이 다르다. ML은 prediction performance에, DS는 큰 data를 한 줄로 요약하고 해석하는 analysis에 초점을 둔다. 같은 linear regression도 coefficient의 유의성을 보면 analysis이고, 새 관측값의 $y$를 예측하는 데 쓰면 prediction이다. 이 책의 대부분은 ML의 관점이지만, 그 도구는 통계학의 것이다.
1.8Linear regression 다시 보기
Design matrix $\bX\in\R^{n\times(p+1)}$(첫 column은 intercept를 위한 1), response $\by\in\R^n$에 대해 model은 $\by=\bX\bbeta+\beps$, $\beps\sim\N(\mathbf 0,\sigma^2\bI)$이다.
$\bX$가 full column rank이면 least squares estimator $$\hat\bbeta = \argmin_\bbeta \|\by-\bX\bbeta\|_2^2 = (\bX^\top\bX)^{-1}\bX^\top\by$$ 가 유일하게 존재하며, 이는 Gaussian error 가정 하의 MLE와 같다. 또한 $\hat\bbeta\sim\N\big(\bbeta,\ \sigma^2(\bX^\top\bX)^{-1}\big)$이다.
$J(\bbeta)=\|\by-\bX\bbeta\|^2 = \by^\top\by - 2\bbeta^\top\bX^\top\by + \bbeta^\top\bX^\top\bX\bbeta$. Gradient $\nabla J = -2\bX^\top\by + 2\bX^\top\bX\bbeta = \mathbf 0$에서 normal equation $\bX^\top\bX\bbeta=\bX^\top\by$를 얻는다. Hessian $2\bX^\top\bX$는 full column rank일 때 positive definite이므로($\mathbf v^\top\bX^\top\bX\mathbf v=\|\bX\mathbf v\|^2>0$ for $\mathbf v\ne\mathbf 0$) $J$는 strictly convex이고 해는 유일하다. Gaussian log-likelihood는 $-\frac{1}{2\sigma^2}\|\by-\bX\bbeta\|^2 + C$이므로 maximizer가 같다. 마지막으로 $\hat\bbeta=(\bX^\top\bX)^{-1}\bX^\top(\bX\bbeta+\beps)=\bbeta+(\bX^\top\bX)^{-1}\bX^\top\beps$는 Gaussian의 linear transform이므로 Gaussian이고, covariance는 $(\bX^\top\bX)^{-1}\bX^\top(\sigma^2\bI)\bX(\bX^\top\bX)^{-1}=\sigma^2(\bX^\top\bX)^{-1}$이다.
기하학적으로 fitted value $\hat\by=\bX\hat\bbeta=\mathbf H\by$, $\mathbf H=\bX(\bX^\top\bX)^{-1}\bX^\top$은 $\by$를 $\bX$의 column space에 orthogonal projection한 것이고, residual $\by-\hat\by$는 column space와 orthogonal하다(normal equation이 바로 $\bX^\top(\by-\bX\hat\bbeta)=\mathbf 0$이다).
Linear regression은 closed form solution을 가진다. 이 점이 deep learning과의 가장 큰 차이다. Neural network의 loss는 non-convex이고 closed form이 없으므로 iterative optimization(Chapter 4)으로만 풀 수 있다.
One-hot encoding과 dummy variable trap
Closed form은 $\bX^\top\bX$가 invertible일 때만 존재한다. $\operatorname{rank}(\bX^\top\bX)=\operatorname{rank}(\bX)$이므로 $\bX$의 column이 linearly dependent하면 $\bX^\top\bX$는 singular이고 해가 유일하지 않다. 예를 들어 어떤 column이 모든 sample에서 같은 값을 가지면 intercept column의 상수배가 되어 dependence가 생긴다.
범주가 3개인 변수를 one-hot encoding $[1,0,0],[0,1,0],[0,0,1]$으로 넣으면 세 column의 합이 항상 1, 즉 intercept column과 같아져 linear dependence가 생긴다. 다른 column들로 나머지 한 column을 계산할 수 있기 때문이다. 그래서 regression에서는 한 범주를 reference로 빼는 dummy encoding $[0,0],[1,0],[0,1]$을 쓴다. 이때 각 계수는 reference 범주 대비 차이로 해석된다.
Deep learning에서는 이런 제약 없이 그냥 one-hot을 쓴다. Gradient descent는 $\bX^\top\bX$의 inverse를 요구하지 않고, parameter가 identifiable하지 않아도 prediction function만 잘 학습되면 되기 때문이다. Singular한 문제에서 gradient descent를 0에서 시작하면 해 집합 중 minimum-norm solution으로 수렴한다는 것도 알려져 있다. 같은 이유로 deep learning은 parameter가 data보다 많은 overparameterized model을 문제없이 학습한다.
Logistic regression
Binary response $y\in\{0,1\}$에 대해 $y\mid\bx\sim\text{Bernoulli}(\pi(\bx))$, $\pi(\bx)=\sigma(\bx^\top\bbeta)$, $\sigma(z)=1/(1+e^{-z})$로 둔 model이 logistic regression이다. $\log\frac{\pi}{1-\pi}=\bx^\top\bbeta$이므로 계수 $\beta_j$는 $x_j$가 1 증가할 때 log-odds의 증가량이다. Log-likelihood는 $$\ell(\bbeta)=\sum_{i=1}^n \big[y_i\log\pi_i + (1-y_i)\log(1-\pi_i)\big],\qquad\pi_i=\sigma(\bx_i^\top\bbeta).$$ $\sigma'(z)=\sigma(z)(1-\sigma(z))$를 쓰면 gradient와 Hessian은 $$\nabla\ell(\bbeta)=\sum_i(y_i-\pi_i)\bx_i=\bX^\top(\by-\boldsymbol\pi),\qquad\nabla^2\ell(\bbeta)=-\sum_i\pi_i(1-\pi_i)\bx_i\bx_i^\top=-\bX^\top\mathbf W\bX,$$ $\mathbf W=\diag(\pi_i(1-\pi_i))$이다. Hessian이 negative semidefinite이므로 $\ell$은 concave이지만, score equation $\bX^\top(\by-\boldsymbol\pi)=\mathbf 0$은 $\bbeta$에 대해 non-linear라 closed form 해가 없다. 그래서 Newton–Raphson $$\bbeta^{(t+1)}=\bbeta^{(t)}+(\bX^\top\mathbf W\bX)^{-1}\bX^\top(\by-\boldsymbol\pi)$$ 으로 푼다. 이 update는 매 step 가중 least squares를 푸는 것과 같아서 IRLS(iteratively reweighted least squares)라고도 한다.
이 log-likelihood의 부호를 바꾸고 $n$으로 나눈 것이 바로 binary cross-entropy이며, logistic regression은 hidden layer가 없는 neural network이다. Gradient가 "(정답 − 예측) × input"의 형태라는 점도 기억해 두자. Chapter 3과 4에서 neural network의 gradient가 정확히 같은 형태로 나타난다.
Chapter 2Regression에서 Neural Network로
Lecture Week 01 (3.2–3.5, 4.1–4.2, 4.8), Week 09
Linear model로 표현할 수 없는 non-linear 관계를 다루려면 무엇이 필요한가? 답은 "linear layer를 쌓고 그 사이에 non-linear function을 끼운다"이다. 이 장에서는 multi-layer perceptron(MLP)을 정의하고, 왜 activation function이 필수인지, 그리고 이 구조가 이론적으로 어떤 function까지 표현할 수 있는지를 다룬다.
2.1Deep learning이 하는 일
Deep learning이 다루는 data와 task를 먼저 정리해 두자. Data domain은 image(3차원 tensor), language(token sequence, embedding까지 2차원), video(4차원), signal과 time series(1–2차원)로 나뉘고, task는 다음과 같다.
| Task 유형 | 예 |
|---|---|
| Classification | Image label 분류(Chapter 6), 문장 감정 분류(Chapter 7) |
| Object detection, segmentation | 물체의 위치(box)와 pixel 단위 영역 찾기(Chapter 6) |
| Generation | Image, video, text 생성(Part IV, Chapter 26) |
| View synthesis, 3D | 몇 장의 사진에서 새 시점의 image나 3D object를 만듦 |
| Prediction (forecasting) | 주가, 날씨 같은 time series의 미래 값 예측 |
전통적인 computer vision에서는 사람이 feature를 설계했다. Edge, 모서리, 색 histogram 같은 feature를 image에서 추출해 feature vector를 만들고, 그 위에 logistic regression이나 SVM을 학습했다(feature engineering). Deep learning은 raw pixel을 그대로 넣고 feature 추출과 분류를 하나의 network로 함께 학습한다(end-to-end learning). Regression처럼 "input의 $j$번째 자리에는 이 feature가 와야 한다"는 설계가 필요 없다는 것이 핵심 차이이다. 이 장은 그 network가 어떤 구조를 가져야 하는지에서 출발한다.
2.2Linear layer를 쌓기만 하면 생기는 문제
Input $\bx\in\R^{d}$에 대한 linear (affine) layer는 $\bx\mapsto \bW\bx+\bb$이다. 표현력을 높이려고 이를 두 번 쌓으면 $$\bW_2(\bW_1\bx+\bb_1)+\bb_2 = (\bW_2\bW_1)\bx + (\bW_2\bb_1+\bb_2) = \tilde\bW\bx+\tilde\bb.$$
Affine map의 composition은 affine map이다. 따라서 activation 없이 $L$개의 linear layer를 쌓은 network는 하나의 linear layer와 표현력이 같다.
즉 깊이만으로는 아무것도 얻지 못한다. MNIST의 $28\times28$ 숫자 image를 784차원 vector로 flatten하여 한 층짜리 linear classifier(multinomial logistic regression)에 넣는 것도 가능하고 어느 정도 동작하지만, 성능이 제한되는 이유가 여기에 있다. Pixel과 label 사이의 관계가 non-linear이기 때문이다. 해결책은 각 layer 사이에 element-wise non-linear function $g$를 넣는 것이다.
$(x_1,x_2)\in\{0,1\}^2$에서 $y=x_1\oplus x_2$(XOR)를 생각하자. $y=1$인 점 $(1,0),(0,1)$과 $y=0$인 점 $(0,0),(1,1)$은 어떤 직선으로도 분리되지 않으므로, logistic regression처럼 decision boundary가 hyperplane인 model은 이를 완벽히 분류할 수 없다. 그러나 ReLU hidden unit 두 개면 충분하다. $$h_1=\mathrm{ReLU}(x_1+x_2),\qquad h_2=\mathrm{ReLU}(x_1+x_2-1),\qquad \hat y=h_1-2h_2.$$ 네 점에서 $\hat y$는 각각 $(0,0)\mapsto0$, $(1,0)\mapsto1$, $(0,1)\mapsto1$, $(1,1)\mapsto2-2=0$이다. Hidden layer가 input을 새 좌표 $(h_1,h_2)$로 옮기면, 그 공간에서는 linear function으로 답을 낼 수 있다.
2.3Multi-layer perceptron
$\ba^{(0)}=\bx$로 두고 $l=1,\dots,L$에 대해 $$\bz^{(l)} = \bW^{(l)}\ba^{(l-1)}+\bb^{(l)},\qquad \ba^{(l)} = g^{(l)}\big(\bz^{(l)}\big)$$ 로 정의되는 function $f_\theta(\bx)=\ba^{(L)}$을 multi-layer perceptron(MLP) 또는 fully-connected network라 한다. $\bW^{(l)}\in\R^{d_l\times d_{l-1}}$은 weight, $\bb^{(l)}\in\R^{d_l}$은 bias, $\bz^{(l)}$은 pre-activation(net input), $g^{(l)}$은 activation function, $\theta=\{\bW^{(l)},\bb^{(l)}\}_{l=1}^L$이다. $l\lt L$인 layer를 hidden layer라 한다.
Parameter 수는 $\sum_{l=1}^L d_l(d_{l-1}+1)$이다. 예를 들어 $28\times28$ image(784차원)를 hidden 256, 256을 거쳐 10개 class로 보내는 MLP는 $256\cdot785+256\cdot257+10\cdot257 = 269{,}322$개의 parameter를 가진다.
Classification에서 마지막 layer의 activation은 보통 softmax $$\softmax(\bz)_k = \frac{e^{z_k}}{\sum_{j=1}^K e^{z_j}}$$ 이다. Output은 각 성분이 양수이고 합이 1이므로 categorical distribution의 parameter로 해석된다. Softmax에 들어가기 직전의 값 $\bz^{(L)}$을 logit이라 부른다. $K=2$이면 $\softmax(\bz)_1=\sigma(z_1-z_2)$로 sigmoid와 같아진다.
Softmax는 모든 logit에 같은 상수를 더해도 변하지 않는다. $\softmax(\bz+c\mathbf 1)_k=e^{z_k+c}/\sum_je^{z_j+c}=\softmax(\bz)_k$이기 때문이다(shift invariance). 그래서 logit 자체의 절대적 크기는 의미가 없고 차이만 의미가 있다. 수치 계산에서는 $c=-\max_jz_j$로 두어 $e^{z}$의 overflow를 막는다. 같은 이유로 $\log\softmax(\bz)_k=z_k-\log\sum_je^{z_j}$를 한 번에 계산하는 log-sum-exp trick을 쓴다.
2.4Activation functions
| Name | $g(z)$ | $g'(z)$ | Range |
|---|---|---|---|
| Sigmoid | $\sigma(z)=\dfrac{1}{1+e^{-z}}$ | $\sigma(z)(1-\sigma(z))$ | $(0,1)$ |
| Tanh | $\tanh z$ | $1-\tanh^2 z$ | $(-1,1)$ |
| ReLU | $\max(0,z)=\dfrac{z+|z|}{2}$ | $\ind[z>0]$ | $[0,\infty)$ |
| Leaky ReLU | $\max(\alpha z, z)$ | $1$ or $\alpha$ | $\R$ |
| GELU | $z\,\Phi(z)$ | $\Phi(z)+z\phi(z)$ | $\approx[-0.17,\infty)$ |
Sigmoid는 $\max_z\sigma'(z)=\sigma'(0)=1/4$이다. Chapter 4에서 보듯 backpropagation은 layer마다 activation의 derivative를 곱하므로, sigmoid를 쓰면 layer 하나를 지날 때마다 이 factor가 1/4 이하로 곱해져 깊은 network에서 gradient가 지수적으로 작아지기 쉽다. 또 $|z|$가 크면 $\sigma'(z)\approx0$이 되는 saturation이 생긴다. ReLU는 $z>0$ 구간에서 derivative가 정확히 1이라 이 문제가 없고 계산도 싸서 hidden layer의 기본값이 되었다. $z=0$에서 미분 불가능하지만 실제로는 subgradient(보통 0)를 쓴다. Transformer 계열에서는 매끄러운 GELU를 많이 쓴다. 여기서 $\Phi,\phi$는 standard normal의 cdf, pdf이다.
2.5Universal Approximation Theorem
"Non-linearity를 넣으면 non-linear 관계를 표현할 수 있다"는 직관을 정확히 말하면 다음과 같다.
$g:\R\to\R$가 continuous이고 polynomial이 아니라고 하자. Compact set $K\subset\R^d$ 위의 임의의 continuous function $f:K\to\R$와 임의의 $\varepsilon>0$에 대해, 어떤 $N$과 $\alpha_i,b_i\in\R$, $\bw_i\in\R^d$가 존재하여 $$\sup_{\bx\in K}\Big|f(\bx)-\sum_{i=1}^N \alpha_i\, g(\bw_i^\top\bx+b_i)\Big| \lt \varepsilon.$$
즉 hidden layer가 하나뿐인 MLP도 width $N$을 충분히 키우면 어떤 continuous function이든 원하는 정확도로 근사할 수 있다. Polynomial activation이 제외되는 이유는 차수 $m$인 polynomial $g$에 대해 $\sum_i\alpha_ig(\bw_i^\top\bx+b_i)$가 여전히 차수 $m$ 이하의 polynomial이라 표현력이 유한 차원 공간에 갇히기 때문이다.
1차원 ReLU의 경우는 직접 구성해 볼 수 있다. $f$가 $[a,b]$에서 continuous이면 uniformly continuous이므로, 충분히 촘촘한 격자 $a=t_0\lt t_1\lt\cdots\lt t_N=b$에서 $f$를 선형 보간한 piecewise linear function $\hat f$는 $\sup|f-\hat f|\lt\varepsilon$을 만족한다. 그런데 꺾이는 점이 $t_1,\dots,t_{N-1}$인 piecewise linear function은 $$\hat f(x)=f(t_0)+s_0\,(x-t_0)+\sum_{k=1}^{N-1}(s_k-s_{k-1})\,\mathrm{ReLU}(x-t_k),\qquad x\in[a,b]$$ ($s_k$는 $k$번째 구간의 기울기)로 정확히 쓸 수 있다. $x-t_0=\mathrm{ReLU}(x-t_0)$이므로 이는 hidden unit $N$개짜리 ReLU network이다. 꺾이는 점마다 ReLU 하나가 기울기를 바꾸는 역할을 한다.
이 정리는 존재성만 보장한다. (1) 필요한 $N$이 얼마나 큰지, (2) gradient descent로 그 weight를 찾을 수 있는지, (3) 유한 sample로 학습한 결과가 generalize되는지는 말하지 않는다. 실제로 필요한 $N$은 차원에 대해 지수적으로 커질 수 있다. 반면 depth를 늘리면 같은 function을 훨씬 적은 parameter로 표현할 수 있는 경우가 알려져 있다(depth separation; Telgarsky 2016은 depth $k^3$ network가 표현하는 어떤 function을 depth $k$ network로 근사하려면 width가 $2^k$ 수준으로 필요함을 보였다). 깊게 쌓는 것이 넓게 펼치는 것보다 효율적이라는 것이 deep learning의 "deep"이 가지는 의미이다.
Depth의 이점은 간단한 예로 볼 수 있다. Tent map $T(x)=2\,\mathrm{ReLU}(x)-4\,\mathrm{ReLU}(x-\tfrac12)$는 $[0,1]$에서 $0\to1\to0$으로 올라갔다 내려오는 함수로, ReLU 2개짜리 layer 하나이다. 이를 $k$번 합성한 $T^{\circ k}$는 $[0,1]$에서 $2^k$개의 linear piece를 가진 톱니 모양 함수가 된다. Depth $k$, layer당 unit 2개, 즉 parameter $O(k)$로 $2^k$개의 piece를 만든 것이다. 반면 hidden layer 하나짜리 ReLU network는 unit이 $N$개이면 1차원에서 piece가 최대 $N+1$개이므로(꺾이는 점이 unit마다 하나) 같은 함수를 표현하려면 $2^k-1$개 이상의 unit이 필요하다. 합성(composition)은 구조를 반복해서 재사용하므로 표현력을 지수적으로 늘린다.
2.6Forward process
Input이 network를 통과해 output이 계산되는 과정을 forward process(forward pass)라 한다. Hidden 1의 경우를 성분으로 쓰면 $$z^{(1)}_j = \sum_{i} w^{(1)}_{j,i}\,x_i + b^{(1)}_j,\qquad a^{(1)}_j = g\big(z^{(1)}_j\big),$$ 즉 $\bz^{(1)}=\bW^{(1)}\bx+\bb^{(1)}$이다. Mini-batch $\bX\in\R^{B\times d}$(row가 sample)를 한꺼번에 처리할 때는 $\bZ=\bX\bW^\top+\mathbf{1}\bb^\top$처럼 행렬 곱 하나로 계산되며, GPU가 deep learning에 유리한 이유가 이것이다.
2.7Encoder, Classifier, Representation
Classification network $f_\theta$는 대개 두 부분으로 나눠 생각한다. $$f_\theta(\bx) = \softmax\big(C_{\theta_1}(E_{\theta_2}(\bx))\big).$$ Encoder $E$는 고차원 input(예: $3\times224\times224$ image)을 $D$차원 vector $\bh=E(\bx)$로 보내고, classifier $C$는 보통 linear layer 하나로 $\bh$를 logit으로 보낸다. 이 $\bh$를 문맥에 따라 feature, representation, latent vector, embedding이라 부르고, CNN 중간 출력처럼 공간 구조가 남아 있으면 feature map이라 한다.
Classifier가 linear이므로, 학습이 잘 되었다는 것은 encoder가 class들을 linearly separable한 representation으로 보냈다는 뜻이다. 다시 말해 encoder는 label과 관련 있는 정보만 남기는 dimension reduction이다. 이 관점은 transfer learning(Chapter 12)과 generative model(Part IV)의 바탕이 된다.
2.8$f_\theta(x)$와 $p_\theta(y\mid x)$
같은 network를 두 가지 방식으로 표기한다.
- $\by=f_\theta(\bx)$: deterministic function. 주어진 $\bx$에 대해 하나의 output vector를 계산한다.
- $p_\theta(y\mid\bx)$: conditional distribution. $\bx$가 주어졌을 때 label $y$의 distribution이며, $\bx$와 $y$ 모두의 function이다.
둘의 관계는 "network output이 distribution의 parameter"라는 것이다. Classification에서는 $p_\theta(y=k\mid\bx)=f_\theta(\bx)_k$, 즉 softmax output의 $k$번째 성분이고, regression에서는 $p_\theta(y\mid\bx)=\N(y; f_\theta(\bx),\sigma^2)$이다. 이 대응이 다음 장에서 loss function을 likelihood로부터 유도하는 열쇠가 된다.
Chapter 3Loss Function: Likelihood와 Information
Lecture Week 01 (4.3), Week 09, Week 11
Loss function은 임의로 고르는 것이 아니다. Network output을 distribution의 parameter로 보고 MLE를 적용하면 mean squared error(MSE)와 cross-entropy(CE)가 자연스럽게 나온다. 같은 cross-entropy를 information theory 쪽에서 유도할 수도 있으며, 두 유도는 KL divergence를 통해 하나로 만난다.
3.1왜 accuracy가 아니라 loss인가
Classification의 최종 목적은 accuracy이지만, accuracy $\frac1n\sum_i \ind[\hat y_i=y_i]$는 $\theta$에 대해 piecewise constant이다. Gradient가 거의 모든 곳에서 0이므로 gradient-based optimization에 쓸 수 없다. 그래서 미분 가능한 surrogate인 loss function $\L(\theta)$를 minimize한다. Loss는 model weight를 estimate하는 기준이며, 학습이란 loss를 가장 작게 만드는 weight를 찾는 것이다. Linear regression에서 least squares가 하던 역할과 같다.
3.2Conditional MLE로부터의 유도
Training data $\{(\bx_i,y_i)\}_{i=1}^n$이 iid라 하고, $y\mid\bx$의 distribution을 network output으로 parameterize한다. Conditional log-likelihood는 $$\ell(\theta)=\sum_{i=1}^n\log p_\theta(y_i\mid\bx_i),\qquad \hat\theta=\argmax_\theta\ell(\theta)=\argmin_\theta\Big[-\frac1n\sum_{i=1}^n\log p_\theta(y_i\mid\bx_i)\Big].$$ 대괄호 안이 negative log-likelihood(NLL)이며, 어떤 distribution을 가정하느냐에 따라 익숙한 loss가 된다.
Gaussian → MSE
$y\mid\bx\sim\N(f_\theta(\bx),\sigma^2)$, $\sigma^2$ 고정이면 $$-\log p_\theta(y\mid\bx) = \frac{(y-f_\theta(\bx))^2}{2\sigma^2}+\frac12\log(2\pi\sigma^2).$$ 상수를 버리면 NLL의 minimization은 $\frac1n\sum_i(y_i-f_\theta(\bx_i))^2$의 minimization, 즉 MSE와 같다. $\sigma$까지 network가 출력하게 하면($\omega=(\mu,\sigma)=f_\theta(\bx)$) loss는 $\log\sigma+\frac{(y-\mu)^2}{2\sigma^2}$가 되어 heteroscedastic regression이 된다.
Bernoulli → Binary cross-entropy
$y\in\{0,1\}$, $y\mid\bx\sim\text{Bernoulli}(\pi_\theta(\bx))$, $\pi_\theta=\sigma\circ f_\theta$이면 $p_\theta(y\mid\bx)=\pi_\theta(\bx)^{y}(1-\pi_\theta(\bx))^{1-y}$이고 $$\ell(\theta)=\sum_{i=1}^n\Big[y_i\log\pi_\theta(\bx_i)+(1-y_i)\log\big(1-\pi_\theta(\bx_i)\big)\Big].$$ 부호를 바꾸고 $n$으로 나눈 것이 binary cross-entropy(BCE)이다. Hidden layer가 없으면($f_\theta(\bx)=\bx^\top\bbeta$) 이는 정확히 logistic regression의 MLE이다.
한 sample이 여러 label을 동시에 가질 수 있는 multi-label classification(예: 한 image에 고양이와 소파가 함께 있음)에서는 class마다 독립적인 Bernoulli를 두어 $p_\theta(\by\mid\bx)=\prod_k\pi_k^{y_k}(1-\pi_k)^{1-y_k}$로 model한다. Loss는 class별 BCE의 합이며, output에 softmax가 아니라 class마다 sigmoid를 쓴다.
Categorical → Cross-entropy
$K$-class에서 label을 one-hot vector $\by_i\in\{0,1\}^K$로 쓰고 $y\mid\bx\sim\text{Categorical}(\bp_\theta(\bx))$, $\bp_\theta=\softmax\circ f_\theta$라 하면 $p_\theta(y\mid\bx)=\prod_{k}p_{\theta,k}(\bx)^{y_k}$이므로 $$\text{CE}=-\frac1N\sum_{i=1}^N\sum_{k=1}^K y_{ik}\log p_{ik}.$$ ($N$은 batch size, $K$는 class 수.) One-hot이므로 실제로는 정답 class의 $-\log p_{i,y_i}$만 남는다. 예를 들어 output이 $(0.1,0.5,0.2,0.2)$이고 정답이 두 번째 class이면 loss는 $-\log 0.5$이고, 학습은 이 0.5를 1에 가깝게 만드는 $\theta$를 찾는 과정이다.
MLE에서는 data $X$가 따르는 distribution의 parameter $\theta$를 찾는다. Deep learning에서는 network로 parameterize된 $y$의 conditional distribution, 즉 $T\sim\text{distribution}(\mu=f_\theta(\bx))$의 parameter를 결정하는 $\theta$(또는 function $f_\theta$ 자체)를 찾는다. Target이 Gaussian이면 MSE, Bernoulli이면 BCE, categorical이면 CE이다.
3.3Information theory
같은 cross-entropy를 "놀라움의 양"에서 출발해 유도할 수 있다. Discrete random variable $X$의 outcome $x$가 가지는 information(degree of surprise) $h(x)$가 다음을 만족해야 한다고 하자.
- $h$는 $p(x)$에만 의존하며 $p(x)$에 대해 decreasing이다. 드문 사건이 일어나면 정보가 많다.
- 독립 사건 $A,B$에 대해 $h(A\cap B)=h(A)+h(B)$이다.
$h(x)=\phi(p(x))$라 쓰면 조건 2는 $\phi(pq)=\phi(p)+\phi(q)$이다. $\psi(u)=\phi(e^{-u})$로 두면 $\psi(u+v)=\psi(u)+\psi(v)$(Cauchy functional equation)이고, monotone 해는 linear뿐이므로 $\phi(p)=-c\log p$, $c>0$이다. $c=1$(단위 nat)로 둔다.
$h(x)=-\log p(x)$를 self-information이라 하고, 그 expectation $$H(X)=\E[h(X)]=-\sum_x p(x)\log p(x)$$ 를 Shannon entropy라 한다.
$X$가 $n$개의 값을 가지면 $0\le H(X)\le\log n$이다. 하한은 어떤 $p_i=1$일 때, 상한은 $p_i=1/n$ (uniform)일 때 달성된다.
$0\le p_i\le1$이므로 $-p_i\log p_i\ge0$이고, 등호는 각 $p_i\in\{0,1\}$일 때뿐이다. 상한은 $\log$의 concavity와 Jensen's inequality로 $H(X)=\E\big[\log\frac{1}{p(X)}\big]\le\log\E\big[\frac1{p(X)}\big]=\log\sum_{i:p_i>0}1\le\log n$. 등호는 $1/p(X)$가 상수, 즉 uniform일 때이다. (강의에서처럼 constraint $\sum p_i=1$ 하에 Lagrange multiplier로 $\partial_{p_i}[-\sum p\log p+\lambda(\sum p-1)]=-\log p_i-1+\lambda=0$을 풀어도 모든 $p_i$가 같다는 결론을 얻는다.)
두 distribution $p,q$에 대해 $$H(p,q)=-\sum_x p(x)\log q(x)=-\E_{p}[\log q(X)],\qquad \KL(p\,\|\,q)=\sum_x p(x)\log\frac{p(x)}{q(x)}.$$ Continuous인 경우 합을 적분으로 바꾼다.
정의에서 바로 다음 분해가 나온다. $$H(p,q)=H(p)+\KL(p\,\|\,q).$$ $H(p,q)$는 "실제 분포가 $p$인데 $q$를 기준으로 부호화했을 때의 평균 비용"이고, $\KL$은 그중 $q$가 틀려서 생긴 초과분이다.
$\KL(p\,\|\,q)\ge0$이고, 등호는 $p=q$일 때만 성립한다.
$-\log$는 strictly convex이므로 Jensen에 의해 $\KL(p\|q)=\E_p\big[-\log\frac{q(X)}{p(X)}\big]\ge-\log\E_p\big[\frac{q(X)}{p(X)}\big]=-\log\sum_{x:p(x)>0}q(x)\ge-\log1=0.$ 등호는 $q/p$가 $p$-a.s. 상수이고 $q$의 mass가 $p$의 support 밖에 없을 때, 즉 $p=q$일 때이다.
KL은 0 이상이고 같을 때만 0이지만 distance(metric)가 아니다. Symmetric하지 않고($\KL(p\|q)\ne\KL(q\|p)$) triangle inequality도 성립하지 않는다. 예를 들어 $p=\text{Bern}(1/2)$, $q=\text{Bern}(1/4)$이면 $\KL(p\|q)=\frac12\log2+\frac12\log\frac23\approx0.144$, $\KL(q\|p)=\frac14\log\frac12+\frac34\log\frac32\approx0.131$이다.
Continuous random variable의 entropy $h(X)=-\int f\log f$(differential entropy)는 discrete의 경우와 달리 음수일 수 있다(예: $\mathrm{Uniform}(0,a)$의 entropy는 $\log a$이므로 $a\lt1$이면 음수이다). 그러나 KL divergence는 continuous에서도 항상 0 이상이고 좌표 변환에 불변이므로, deep learning의 이론에서는 주로 KL을 다룬다. 다음은 이후 VAE와 diffusion에서 반복해서 쓰는 공식이다.
$d$차원 Gaussian $p=\N(\bmu_1,\bSigma_1)$, $q=\N(\bmu_2,\bSigma_2)$에 대해 $$\KL(p\,\|\,q)=\frac12\Big[\tr(\bSigma_2^{-1}\bSigma_1)+(\bmu_2-\bmu_1)^\top\bSigma_2^{-1}(\bmu_2-\bmu_1)-d+\log\frac{\det\bSigma_2}{\det\bSigma_1}\Big].$$ 특히 1차원이면 $\KL=\log\frac{\sigma_2}{\sigma_1}+\frac{\sigma_1^2+(\mu_1-\mu_2)^2}{2\sigma_2^2}-\frac12$이고, 두 covariance가 같은 $\sigma^2\bI$이면 $\KL=\frac{\|\bmu_1-\bmu_2\|^2}{2\sigma^2}$이다.
$\log p(\bx)-\log q(\bx)=\frac12\log\frac{\det\bSigma_2}{\det\bSigma_1}-\frac12(\bx-\bmu_1)^\top\bSigma_1^{-1}(\bx-\bmu_1)+\frac12(\bx-\bmu_2)^\top\bSigma_2^{-1}(\bx-\bmu_2)$. $\bx\sim p$에 대해 expectation을 취한다. $\E_p[(\bx-\bmu_1)^\top\bSigma_1^{-1}(\bx-\bmu_1)]=\tr(\bSigma_1^{-1}\bSigma_1)=d$. $\bx-\bmu_2=(\bx-\bmu_1)+(\bmu_1-\bmu_2)$로 쓰면 $\E_p[(\bx-\bmu_2)^\top\bSigma_2^{-1}(\bx-\bmu_2)]=\tr(\bSigma_2^{-1}\bSigma_1)+(\bmu_1-\bmu_2)^\top\bSigma_2^{-1}(\bmu_1-\bmu_2)$(cross term의 expectation은 0). 합치면 된다.
3.4두 유도가 만나는 지점
Classification에서 sample 하나의 label을 one-hot $p=\by$로, model output을 $q=\bp_\theta(\bx)$로 두면 $H(\by,\bp_\theta)=-\sum_k y_k\log p_{\theta,k}$로 앞의 CE와 정확히 같다. One-hot의 entropy는 0이므로 $H(\by,\bp_\theta)=\KL(\by\|\bp_\theta)$이기도 하다.
더 일반적으로, data가 실제 distribution $p_{\text{data}}$에서 iid로 나온다고 하자. Population 수준에서 $$\E_{p_{\text{data}}}[\log p_\theta(X)]=-H(p_{\text{data}},p_\theta)=-H(p_{\text{data}})-\KL(p_{\text{data}}\,\|\,p_\theta)$$ 이고, $H(p_{\text{data}})$는 $\theta$와 무관하므로 $$\boxed{\;\argmax_\theta\E_{p_{\text{data}}}[\log p_\theta(X)]=\argmin_\theta H(p_{\text{data}},p_\theta)=\argmin_\theta \KL(p_{\text{data}}\,\|\,p_\theta)\;}$$ 이다. 실제로 계산하는 average log-likelihood $\frac1n\sum_i\log p_\theta(x_i)$는 왼쪽 expectation의 Monte Carlo estimate이며(empirical distribution $\hat p_{\text{data}}=\frac1n\sum_i\delta_{x_i}$에 대한 expectation이라 쓸 수 있다), LLN에 의해 $n\to\infty$에서 수렴한다. Data가 discrete이면 $\hat p_{\text{data}}$의 entropy가 잘 정의되므로 $\argmax\frac1n\sum\log p_\theta(x_i)=\argmin\KL(\hat p_{\text{data}}\|p_\theta)$가 정확히 성립한다. 따라서 MLE, cross-entropy minimization, KL minimization은 같은 문제다. Cross-entropy로 학습한다는 것은 model distribution을 data distribution 쪽으로 끌어당긴다는 뜻이며, 이 등식은 Part IV의 generative model에서 그대로 다시 쓰인다.
3.5Conditional entropy
강의 노트에서 손으로 유도한 conditional entropy도 정리해 둔다. $H(Y\mid X=x)=-\sum_y p(y\mid x)\log p(y\mid x)$의 $X$에 대한 평균을 $$H(Y\mid X)=\sum_x p(x)H(Y\mid X=x)=-\sum_{x,y}p(x,y)\log\frac{p(x,y)}{p(x)}=H(X,Y)-H(X)$$ 로 정의한다(chain rule of entropy). 여기서 mutual information $I(X;Y)=H(Y)-H(Y\mid X)=\KL\big(p(x,y)\,\|\,p(x)p(y)\big)\ge0$가 나오며, Chapter 12의 contrastive learning에서 사용한다.
3.6Softmax–CE의 gradient
Logit $\bz\in\R^K$, $\bp=\softmax(\bz)$, one-hot label $\by$에 대해 $\ell(\bz)=-\sum_k y_k\log p_k$이면 $$\frac{\partial\ell}{\partial\bz}=\bp-\by.$$
$\log p_k=z_k-\log\sum_j e^{z_j}$이므로 $\ell=-\sum_k y_kz_k+\big(\sum_k y_k\big)\log\sum_je^{z_j}=-\by^\top\bz+\log\sum_je^{z_j}$ ($\sum_k y_k=1$). 미분하면 $-y_m+e^{z_m}/\sum_je^{z_j}=p_m-y_m$.
Gradient가 "예측 확률 − 정답"이라는 단순한 형태라는 점이 중요하다. Logistic regression의 score equation $\sum_i(y_i-\pi_i)\bx_i=0$과 같은 구조이며, Gaussian–MSE 조합의 gradient $f_\theta(\bx)-y$와도 같은 모양이다. 이는 우연이 아니다. Gaussian, Bernoulli, categorical은 모두 exponential family $p(y\mid\eta)=h(y)\exp\{\eta^\top T(y)-A(\eta)\}$에 속하고, network의 마지막 output을 natural parameter $\eta$로 두는 것(identity, sigmoid, softmax가 각각 canonical link의 역함수이다)이 바로 위의 세 조합이다. 이때 $-\log p=-\eta^\top T(y)+A(\eta)+\text{const}$이므로 $$\frac{\partial(-\log p)}{\partial\eta}=\nabla A(\eta)-T(y)=\E[T(Y)]-T(y)$$ 이고, exponential family의 성질 $\nabla A(\eta)=\E_\eta[T(Y)]$에 의해 "예측된 평균 − 관측값"이 된다. GLM 이론의 canonical link가 deep learning의 output layer 설계 원리와 같다.
잘못된 조합을 쓰면 문제가 생긴다. Sigmoid output $\pi=\sigma(z)$에 MSE $\frac12(\pi-y)^2$를 붙이면 $$\frac{\partial}{\partial z}\tfrac12(\pi-y)^2=(\pi-y)\,\sigma'(z)=(\pi-y)\,\pi(1-\pi)$$ 이다. 정답이 $y=1$인데 model이 $z\to-\infty$로 크게 틀리면 $\pi\to0$이므로 gradient도 0으로 간다. 가장 크게 틀린 sample에서 학습이 멈추는 것이다. BCE를 쓰면 $\partial/\partial z=\pi-y\to-1$로, 크게 틀릴수록 강한 신호를 받는다. Classification에 MSE가 아니라 CE를 쓰는 이유이다.
Chapter 4Optimization과 Training
Lecture Week 01 (4.4–4.7), Week 03 (2.4–2.5), Week 05 (1.1), Week 07
Loss를 정했으면 이제 그것을 minimize하는 $\theta$를 찾아야 한다. Neural network의 loss는 non-convex이고 closed form 해가 없으므로 gradient를 따라 조금씩 이동하는 iterative method를 쓴다. 이 장은 gradient descent의 원리, gradient를 효율적으로 계산하는 backpropagation, 그리고 실제 학습을 가능하게 하는 optimizer·initialization·normalization·regularization 기법을 다룬다.
4.1Gradient descent: Taylor 근사에서 출발하기
$\L(\theta)$를 현재 점 $\theta$ 근처에서 first-order Taylor expansion하면 $$\L(\theta+\Delta\theta)\approx\L(\theta)+\nabla\L(\theta)^\top\Delta\theta.$$ $\Delta\theta=-\eta\nabla\L(\theta)$ ($\eta>0$)로 두면 $$\L(\theta+\Delta\theta)-\L(\theta)\approx-\eta\|\nabla\L(\theta)\|^2\le0.$$ 즉 gradient의 반대 방향으로 조금 이동하면 loss가 줄어든다. 이것이 gradient descent $$\theta_{t+1}=\theta_t-\eta\nabla\L(\theta_t)$$ 이며, $\eta$를 learning rate라 한다. 위 논리는 1차 근사이므로 $\eta$가 작을 때만 유효하다. 얼마나 작아야 하는지는 다음 정리가 답한다.
$\nabla\L$이 $\beta$-Lipschitz, 즉 $\|\nabla\L(\theta)-\nabla\L(\theta')\|\le\beta\|\theta-\theta'\|$이면 모든 $\theta$에 대해 $$\L\big(\theta-\eta\nabla\L(\theta)\big)\le\L(\theta)-\eta\Big(1-\frac{\beta\eta}{2}\Big)\|\nabla\L(\theta)\|^2.$$ 따라서 $0\lt\eta\lt2/\beta$이면 gradient가 0이 아닌 한 loss는 strictly 감소한다.
$\beta$-smoothness로부터 $\L(\theta')\le\L(\theta)+\nabla\L(\theta)^\top(\theta'-\theta)+\frac\beta2\|\theta'-\theta\|^2$ (적분형 Taylor 정리와 Cauchy–Schwarz). $\theta'=\theta-\eta\nabla\L(\theta)$를 대입하면 된다.
같은 가정에서 $\L$이 아래로 유계($\L\ge\L^\ast$)이고 $\eta=1/\beta$이면, gradient descent의 처음 $T$ step에 대해 $$\min_{0\le t\lt T}\|\nabla\L(\theta_t)\|^2\le\frac{2\beta\big(\L(\theta_0)-\L^\ast\big)}{T}.$$
$\eta=1/\beta$이면 descent lemma에서 $\L(\theta_{t+1})\le\L(\theta_t)-\frac{1}{2\beta}\|\nabla\L(\theta_t)\|^2$. $t=0,\dots,T-1$에 대해 더하면 telescoping으로 $\frac1{2\beta}\sum_t\|\nabla\L(\theta_t)\|^2\le\L(\theta_0)-\L(\theta_T)\le\L(\theta_0)-\L^\ast$. 최솟값은 평균 이하이다.
즉 non-convex 함수에서 gradient descent가 보장하는 것은 global minimum이 아니라 stationary point($\nabla\L=0$)로의 수렴이며, 그 속도는 $O(1/T)$이다. 실제 deep network에서는 대부분의 local minimum이 global minimum과 비슷한 loss를 가지며, 문제는 오히려 saddle point와 평평한 영역이라는 것이 경험적으로 알려져 있다.
4.2Backpropagation
Gradient descent에는 모든 parameter에 대한 $\partial\L/\partial\theta$가 필요하다. Parameter가 $P$개일 때 numerical gradient $$\frac{\partial\L}{\partial\theta_j}\approx\frac{\L(\theta+\epsilon e_j)-\L(\theta-\epsilon e_j)}{2\epsilon}$$ 는 $2P$번의 forward pass가 필요하고 $O(\epsilon^2)$의 truncation error와 floating point 오차가 있다. 수억 개 parameter에는 쓸 수 없고, 구현 검증용(gradient check)으로만 쓴다.
Backpropagation은 chain rule을 output에서 input 방향으로 적용해 모든 gradient를 한 번에 계산한다. MLP(Chapter 2의 notation)에서 sample 하나의 loss $\ell$에 대해 error signal $\bdelta^{(l)}=\partial\ell/\partial\bz^{(l)}$을 정의하자.
(a) Output layer: softmax + CE이면 $\bdelta^{(L)}=\bp-\by$.
(b) Recursion: $\bdelta^{(l)}=\big(\bW^{(l+1)\top}\bdelta^{(l+1)}\big)\odot g'\big(\bz^{(l)}\big)$, $l=L-1,\dots,1$.
(c) Parameter gradients: $\dfrac{\partial\ell}{\partial\bW^{(l)}}=\bdelta^{(l)}\ba^{(l-1)\top}$, $\dfrac{\partial\ell}{\partial\bb^{(l)}}=\bdelta^{(l)}$.
(a)는 Theorem 3.7이다. (b): $z^{(l+1)}_k=\sum_j w^{(l+1)}_{kj}g(z^{(l)}_j)+b^{(l+1)}_k$이므로 $\partial z^{(l+1)}_k/\partial z^{(l)}_j=w^{(l+1)}_{kj}g'(z^{(l)}_j)$. Chain rule로 $\delta^{(l)}_j=\sum_k\delta^{(l+1)}_k w^{(l+1)}_{kj}g'(z^{(l)}_j)$. (c): $\partial z^{(l)}_j/\partial w^{(l)}_{ji}=a^{(l-1)}_i$, $\partial z^{(l)}_j/\partial b^{(l)}_j=1$.
$x=1$, $y=1$, $w=0.5$, $b=0$이고 $\hat y=\sigma(wx+b)$, $\ell=(\hat y-y)^2$라 하자.
Forward: $z=wx+b=0.5$, $\hat y=\sigma(0.5)\approx0.6225$, $\ell\approx(0.6225-1)^2\approx0.1425$.
Backward: output 쪽부터 local derivative를 곱해 내려간다.
$$\frac{\partial\ell}{\partial\hat y}=2(\hat y-y)\approx-0.7551,\quad\frac{\partial\hat y}{\partial z}=\hat y(1-\hat y)\approx0.2350,\quad\frac{\partial\ell}{\partial z}=\frac{\partial\ell}{\partial\hat y}\frac{\partial\hat y}{\partial z}\approx-0.1774,$$
$$\frac{\partial\ell}{\partial w}=\frac{\partial\ell}{\partial z}\cdot x\approx-0.1774,\qquad\frac{\partial\ell}{\partial b}=\frac{\partial\ell}{\partial z}\cdot1\approx-0.1774.$$
Learning rate $\eta=1$로 한 step 내려가면 $w\leftarrow0.6774$, $b\leftarrow0.1774$가 되어 $\hat y=\sigma(0.8549)\approx0.7016$으로 정답 1에 가까워진다. Backward pass에서 $\partial\ell/\partial z$를 한 번 계산하면 $w$와 $b$의 gradient에 재사용된다는 점이 backpropagation 효율의 핵심이다.
Forward pass에서 $\bz^{(l)},\ba^{(l)}$을 저장해 두면 backward pass는 forward와 같은 크기의 행렬 곱 몇 번으로 끝난다. 일반적으로 scalar 출력 함수의 gradient 전체를 reverse-mode로 계산하는 비용은 함수 계산 비용의 작은 상수배이다(cheap gradient principle). 대신 중간값을 저장해야 하므로 memory를 많이 쓴다. GPU memory가 batch size를 제한하는 주된 이유이다.
PyTorch 같은 framework는 연산을 computational graph로 기록하고 각 연산의 local derivative를 알고 있어 이 과정을 자동으로 수행한다(automatic differentiation). 실제 연구에서 gradient를 손으로 계산할 일은 없지만, recursion (b)의 구조를 이해해야 vanishing/exploding gradient(Chapter 7)와 ResNet의 skip connection(Chapter 6)이 왜 중요한지 알 수 있다. (b)를 반복하면 $\bdelta^{(1)}$에는 $\prod_l\bW^{(l)\top}\diag(g'(\bz^{(l)}))$라는 행렬 곱이 들어가고, 이 곱의 크기가 depth에 따라 지수적으로 커지거나 작아질 수 있기 때문이다.
4.3Stochastic gradient와 Mini-batch
Empirical loss $\L(\theta)=\frac1n\sum_{i=1}^n\ell_i(\theta)$의 gradient를 매번 전체 data로 계산하는 것을 full-batch gradient descent라 한다. 대신 index set $\mathcal B$ ($|\mathcal B|=B$)를 무작위로 뽑아 $$\hat g=\frac1B\sum_{i\in\mathcal B}\nabla\ell_i(\theta)$$ 를 쓰는 것이 stochastic gradient descent(SGD)이다. $B=1$이면 one-sample(online), $1\lt B\lt n$이면 mini-batch이다.
$\mathcal B$의 원소를 $\{1,\dots,n\}$에서 uniform하게 복원추출로 뽑으면 $\E[\hat g]=\nabla\L(\theta)$이고 $\Cov(\hat g)=\frac1B\Sigma(\theta)$이다. 여기서 $\Sigma(\theta)=\frac1n\sum_i(\nabla\ell_i-\nabla\L)(\nabla\ell_i-\nabla\L)^\top$는 per-sample gradient의 empirical covariance이다.
뽑힌 index $I_1,\dots,I_B$는 iid uniform이므로 각 $\nabla\ell_{I_b}$는 mean $\frac1n\sum_i\nabla\ell_i=\nabla\L$, covariance $\Sigma$인 iid random vector이다. 평균의 성질에서 결론이 나온다. 비복원추출이면 finite population correction에 의해 covariance가 $\frac{n-B}{n-1}\cdot\frac1B\Sigma$가 된다.
즉 mini-batch gradient는 full gradient의 unbiased estimator이고, noise는 $1/\sqrt B$로 줄어든다. 전체 data를 한 바퀴 도는 것을 epoch, parameter를 한 번 update하는 것을 iteration(step)이라 한다. Mini-batch를 쓰는 이유는 계산 효율(GPU 병렬화, memory)뿐 아니라 이 noise 자체가 sharp minimum을 벗어나게 해 generalization에 도움이 된다는 관찰 때문이기도 하다. Batch size를 $k$배 키울 때 learning rate도 $k$배 키우는 linear scaling rule(Goyal et al., 2017)은 "작은 batch로 $k$ step 가는 것과 큰 batch로 한 step 가는 것"의 update 크기를 맞추려는 heuristic이며, 아주 큰 batch에서는 깨진다.
SGD는 gradient에 noise가 있으므로 learning rate를 고정하면 minimum 근처에서 계속 흔들린다. 고전적인 stochastic approximation 이론(Robbins–Monro)에서는 $\sum_t\eta_t=\infty$, $\sum_t\eta_t^2\lt\infty$인 schedule(예: $\eta_t\propto1/t$)에서 수렴이 보장된다. 첫 조건은 충분히 멀리 갈 수 있게, 둘째 조건은 noise가 결국 사라지게 한다. 실무에서 learning rate를 점점 줄이는 schedule(아래)을 쓰는 이유이다.
4.4Optimizers
Plain SGD는 loss surface의 곡률이 방향마다 크게 다르면(ill-conditioned) 좁은 골짜기에서 진동하고 평평한 방향으로는 느리게 움직인다. 이를 보완하는 대표적인 방법은 다음과 같다. $g_t$는 $t$번째 stochastic gradient이다.
| Optimizer | Update | 아이디어 |
|---|---|---|
| Momentum | $v_t=\mu v_{t-1}+g_t$, $\theta_t=\theta_{t-1}-\eta v_t$ | 과거 gradient의 지수 가중 합으로 진동 방향은 상쇄하고 일관된 방향은 가속. Gradient가 상수 $g$이면 effective step은 $\eta g/(1-\mu)$ |
| AdaGrad | $s_t=s_{t-1}+g_t^2$, $\theta_t=\theta_{t-1}-\eta g_t/(\sqrt{s_t}+\epsilon)$ | Coordinate별로 누적 gradient 크기로 나눠 step size를 조정 |
| RMSProp | $s_t=\rho s_{t-1}+(1-\rho)g_t^2$, 나머지 동일 | AdaGrad의 누적을 moving average로 바꿔 learning rate가 0으로 사라지는 문제를 해결 |
| Nesterov (NAG) | $v_t=\mu v_{t-1}+\nabla\L(\theta_{t-1}-\eta\mu v_{t-1})$, $\theta_t=\theta_{t-1}-\eta v_t$ | Momentum으로 미리 이동한 지점에서 gradient를 계산해 overshoot를 줄임 |
| Adadelta | RMSProp의 분모에 더해, 분자도 과거 update 크기의 moving average $\sqrt{\E[\Delta\theta^2]}$로 둠 | Learning rate 없이 단위(unit)가 맞는 update |
| Adam | 아래 참고 | Momentum + RMSProp + bias correction |
- $m_t=\beta_1m_{t-1}+(1-\beta_1)g_t$ (first moment)
- $v_t=\beta_2v_{t-1}+(1-\beta_2)g_t^{\odot2}$ (second moment, element-wise)
- $\hat m_t=m_t/(1-\beta_1^t)$, $\hat v_t=v_t/(1-\beta_2^t)$ (bias correction)
- $\theta_t=\theta_{t-1}-\eta\,\hat m_t/(\sqrt{\hat v_t}+\epsilon)$
기본값 $\beta_1=0.9$, $\beta_2=0.999$, $\epsilon=10^{-8}$.
Bias correction이 필요한 이유: $m_0=0$에서 시작하므로 $g_t$가 stationary하다면 $\E[m_t]=(1-\beta_1)\sum_{s=1}^t\beta_1^{t-s}\E[g]=(1-\beta_1^t)\E[g]$로 초기에 0 쪽으로 치우친다. $(1-\beta_1^t)$로 나누면 unbiased가 된다.
Weight decay($\lambda\|\theta\|^2$ penalty)를 Adam에 그대로 넣으면 penalty의 gradient까지 $\sqrt{\hat v}$로 나뉘어 의도한 효과가 사라진다. AdamW는 decay를 adaptive scaling 밖에서 따로 적용한다: $\theta_t=\theta_{t-1}-\eta\big(\hat m_t/(\sqrt{\hat v_t}+\epsilon)+\lambda\theta_{t-1}\big)$. 현재 Transformer 학습의 기본 optimizer이다.
Learning rate schedule
Learning rate는 가장 중요한 hyperparameter이다. 너무 작으면 minimum까지 아주 많은 update가 필요하고, 적당하면 빠르게 도달하며, 너무 크면 minimum을 넘어 반대편으로 튀면서 발산할 수 있다(descent lemma의 $\eta\lt2/\beta$ 조건). 처음에는 크게, 끝으로 갈수록 작게 하는 것이 일반적이다. Step decay는 정해진 epoch마다 $\eta$를 $1/10$로 줄이고, cosine annealing은 $\eta_t=\eta_{\min}+\frac12(\eta_{\max}-\eta_{\min})\big(1+\cos(\pi t/T)\big)$로 부드럽게 줄인다. 학습 초기 몇백~몇천 step 동안 $\eta$를 0에서 선형으로 올리는 warmup은 Adam의 초기 $\hat v$ 추정이 불안정한 구간을 넘기기 위해 쓰이며, 큰 batch와 Transformer에서 거의 필수이다.
그 밖에 매 epoch 일정 비율로 줄이는 exponential decay, 정해진 step에서 여러 번 줄이는 multi-step, 최솟값과 최댓값 사이를 주기적으로 오가는 cyclic LR(SGDR처럼 cosine을 주기마다 재시작하는 warm restart 포함), 그리고 한 번 크게 올렸다가 내리는 one-cycle policy가 있다. PyTorch의torch.optim.lr_scheduler에 대부분 구현되어 있다.
4.5Weight initialization
학습 시작점 $\theta_0$를 어떻게 잡을까? 모든 weight를 0으로 두면 같은 layer의 unit들이 똑같은 gradient를 받아 영원히 같은 값을 가진다(symmetry). 그래서 random하게 초기화하되, 분산을 잘 골라야 forward의 activation과 backward의 gradient가 layer를 지나며 폭발하거나 사라지지 않는다.
Bias를 0으로 둔 $z^{(l)}_j=\sum_{i=1}^{n_{l-1}}w^{(l)}_{ji}a^{(l-1)}_i$에서 $w$들이 iid, mean 0, $a$와 independent이고 $z^{(l-1)}$이 0에 대해 symmetric하며 $a=\mathrm{ReLU}(z)$라 하자. 그러면 $$\Var\big(z^{(l)}\big)=\tfrac12\,n_{l-1}\Var(w^{(l)})\Var\big(z^{(l-1)}\big).$$ 따라서 $\Var(w^{(l)})=2/n_{l-1}$로 두면 모든 layer에서 pre-activation의 분산이 유지된다.
Independence와 $\E[w]=0$에서 $\Var(w_{ji}a_i)=\E[w^2]\E[a^2]=\Var(w)\E[a^2]$이고, $i\ne k$이면 $\Cov(w_{ji}a_i,w_{jk}a_k)=\E[w_{ji}]\E[w_{jk}]\E[a_ia_k]=0$으로 합의 각 항이 uncorrelated이므로 $\Var(z^{(l)})=n_{l-1}\Var(w)\E[(a^{(l-1)})^2]$. $z^{(l-1)}$이 symmetric이면 $\E[\mathrm{ReLU}(z)^2]=\frac12\E[z^2]=\frac12\Var(z^{(l-1)})$.
Backward 방향도 같은 논리로 분석할 수 있다. Theorem 4.3의 recursion에서 $\delta^{(l)}_j=g'(z^{(l)}_j)\sum_kw^{(l+1)}_{kj}\delta^{(l+1)}_k$이므로 gradient의 분산을 유지하려면 $n_{l+1}\Var(w^{(l+1)})\E[g'^2]=1$이 필요하다. ReLU이면 $\E[g'^2]=1/2$이므로 $\Var(w)=2/n_{\text{out}}$이 된다. Forward와 backward 중 하나를 고르면 되고, PyTorch의 kaiming_normal_은 기본값으로 fan-in($n_{\text{in}}$)을 쓴다.
Tanh처럼 0 근처에서 linear한 activation에는 forward 조건 $\Var(w)=1/n_{\text{in}}$과 backward 조건 $\Var(w)=1/n_{\text{out}}$을 절충한 Xavier (Glorot) initialization $\Var(w)=2/(n_{\text{in}}+n_{\text{out}})$을 쓴다. 다만 현재 실무에서는 대부분 이미 학습된 model(pre-trained model)에서 출발하므로 initialization을 직접 고민할 일은 줄었다(Chapter 12).
4.6Normalization layers
Input을 standardize하면 optimization이 쉬워진다는 것은 regression에서도 알려진 사실이다. Normalization layer는 이것을 network 내부의 모든 layer에서 학습 중에 계속 수행한다.
Mini-batch $\{x_1,\dots,x_B\}$의 한 feature에 대해 $$\mu_{\mathcal B}=\frac1B\sum_i x_i,\quad\sigma^2_{\mathcal B}=\frac1B\sum_i(x_i-\mu_{\mathcal B})^2,\quad\hat x_i=\frac{x_i-\mu_{\mathcal B}}{\sqrt{\sigma^2_{\mathcal B}+\epsilon}},\quad y_i=\gamma\hat x_i+\beta.$$ $\gamma,\beta$는 학습되는 parameter로, 필요하면 normalization을 되돌릴 수 있게 한다.
BatchNorm이 왜 학습을 돕는지는 논쟁이 있다. 원 논문은 앞 layer의 parameter가 바뀌면서 다음 layer input의 distribution이 계속 변하는 internal covariate shift를 줄인다고 설명했지만, 이후 연구(Santurkar et al., 2018)는 loss landscape를 더 매끄럽게(gradient의 Lipschitz 상수를 줄여) 더 큰 learning rate를 가능하게 하는 효과가 더 중요하다고 보았다. 어느 쪽이든 실용적 효과는 분명하다. 더 큰 learning rate, initialization에 대한 둔감함, 약한 regularization 효과(batch 통계의 noise)이다.
BatchNorm은 training과 inference의 동작이 다르다. Training에서는 현재 batch의 통계를 쓰고 running average를 갱신하며, inference(model.eval())에서는 저장된 running average를 쓴다. 원 논문은 inference용 통계를 mini-batch 통계의 평균 $\E[x]=\E_{\mathcal B}[\mu_{\mathcal B}]$, $\Var[x]=\frac{m}{m-1}\E_{\mathcal B}[\sigma^2_{\mathcal B}]$($m$은 batch size, unbiased 보정)로 정의했고, 실제 구현은 이를 exponential moving average로 근사한다. 그러면 inference에서 BatchNorm은 input에 의존하지 않는 고정된 affine 변환 $y=\gamma\frac{x-\E[x]}{\sqrt{\Var[x]+\epsilon}}+\beta$가 되어, 앞 layer의 weight에 합쳐 넣을 수도 있다. Batch 통계를 쓰므로 batch size가 작으면 $\mu_{\mathcal B},\sigma^2_{\mathcal B}$의 추정이 불안정해진다. 이 때문에 batch 축을 쓰지 않는 변형들이 나왔다. CNN의 feature map $(N,C,H,W)$에 대해 어느 축으로 통계를 내는지가 차이이다.
LayerNorm은 sample 하나 안에서 계산하므로 batch size와 무관하고 sequence 길이가 바뀌어도 문제없다. 이것이 Transformer가 LayerNorm을 쓰는 이유이다(Chapter 8). InstanceNorm은 image 하나의 channel별 통계(대비, 색조 등 style 정보)를 제거하므로 style transfer(Chapter 16)에서 쓰인다.
4.7Overfitting과 Regularization
Data를 train / validation / test로 나눈다. Train set으로 $\theta$를 학습하고, validation set으로 hyperparameter(learning rate, epoch 수, model 크기)를 고르며, test set은 마지막에 한 번만 성능을 보고하는 데 쓴다. Train loss는 계속 줄지만 validation loss가 다시 오르기 시작하면 overfitting이다. 이를 막는 기법을 통틀어 regularization이라 한다.
Weight decay = Gaussian prior
Prior $\theta\sim\N(0,\tau^2\bI)$를 두고 posterior mode(MAP)를 구하면 $$\hat\theta_{\text{MAP}}=\argmin_\theta\Big[-\sum_i\log p_\theta(y_i\mid\bx_i)+\frac{1}{2\tau^2}\|\theta\|^2\Big].$$ 즉 L2 penalty(weight decay)는 Gaussian prior의 MAP이고, ridge regression과 같은 구조이다. Laplace prior를 쓰면 L1 penalty(lasso)가 된다.
Dropout
Training 중 각 hidden unit을 확률 $p$로 0으로 만든다. 구현은 inverted dropout으로, mask $m_j\iid\text{Bernoulli}(1-p)$에 대해 $\tilde a_j=\frac{m_j}{1-p}a_j$를 쓴다. 그러면 $\E[\tilde a_j]=a_j$이므로 inference에서는 아무것도 바꾸지 않고 dropout만 끄면 된다(model.eval()). Dropout은 parameter를 공유하는 $2^{(\text{unit 수})}$개 sub-network의 ensemble을 근사하는 것으로 해석된다. 원 논문(Srivastava et al., 2014)은 training 때 scaling하지 않고 unit을 확률 $p_{\text{keep}}$로 유지한 뒤, test 때 weight에 $p_{\text{keep}}$를 곱해 기댓값을 맞추었다. Inverted dropout은 같은 보정을 training 쪽으로 옮긴 것이다. 각 unit이 특정한 다른 unit에 의존하는 co-adaptation을 막아 더 robust한 feature를 배우게 한다는 것이 직관이다.
그 밖의 기법
Early stopping은 validation loss가 가장 낮은 시점의 weight를 쓰는 것이다. Linear model에서는 gradient descent를 일찍 멈추는 것이 L2 regularization과 근사적으로 같다는 결과가 있다. Data augmentation은 label을 바꾸지 않는 변환(회전, crop, 색 변화 등)으로 data를 늘리는 것으로, model에 원하는 invariance를 주입하는 방법이다(Chapter 12).
Parameter가 data보다 훨씬 많은 network가 왜 overfitting하지 않는지, early stopping과 ridge의 관계가 정확히 무엇인지는 다음 장에서 다룬다.
4.8Training loop 요약
지금까지의 내용이 실제 코드에서 어떻게 대응되는지 정리한다(전체 코드는 Appendix A).
| 개념 | PyTorch |
|---|---|
| Mini-batch sampling | for x, y in loader: |
| Forward pass | out = model(x) |
| Loss (NLL) | loss = criterion(out, y) |
| 이전 step의 gradient 초기화 | optimizer.zero_grad() |
| Backpropagation | loss.backward() |
| Parameter update | optimizer.step() |
Chapter 5Generalization: 왜 큰 model이 일반화하는가
새로 추가한 장 (강의 범위 밖). Zhang et al. 2017; Belkin et al. 2019; Hastie et al. 2022; Soudry et al. 2018; Jacot et al. 2018
Chapter 4까지의 도구로 training loss는 거의 0까지 내릴 수 있다. 문제는 그 model이 처음 보는 data에서도 잘 맞느냐이다. 고전적인 통계학은 "parameter 수가 sample 수보다 훨씬 많으면 overfitting한다"고 가르치는데, 현대의 deep network는 parameter가 data보다 수십 배 많고 training data를 완벽하게 외우면서도 test 성능이 좋다. 이 장은 이 현상을 통계학의 언어로 정리한다. 고전적인 uniform convergence bound가 왜 설명에 실패하는지, over-parameterized regime의 double descent, gradient descent가 스스로 고르는 해(implicit regularization), flat minimum과 PAC-Bayes, 그리고 무한히 넓은 network를 kernel method로 보는 neural tangent kernel을 차례로 다룬다. 완결된 이론은 아직 없지만, 각 조각은 정확한 수학으로 말할 수 있다.
5.1Risk, empirical risk, generalization gap
$(X,Y)\sim P$에서 뽑은 data $\{(\bx_i,y_i)\}_{i=1}^n$와 loss $\ell$에 대해, predictor $f$의 risk(population risk)와 empirical risk를 $$R(f)=\E_{(X,Y)\sim P}\big[\ell(f(X),Y)\big],\qquad\hat R_n(f)=\frac1n\sum_{i=1}^n\ell(f(\bx_i),y_i)$$ 로 정의한다. Hypothesis class $\mathcal F$(예: 주어진 architecture가 표현하는 function 전체) 안에서 empirical risk를 최소화하는 것이 empirical risk minimization(ERM), $\hat f=\argmin_{f\in\mathcal F}\hat R_n(f)$이다. Chapter 3의 MLE는 $\ell$이 negative log-likelihood인 ERM이다. $R(\hat f)-\hat R_n(\hat f)$를 generalization gap이라 한다.
Bayes risk $R^\ast=\inf_fR(f)$와 class 안의 최선 $f_{\mathcal F}=\argmin_{f\in\mathcal F}R(f)$를 두면, 실제로 얻은 $\tilde f$(optimizer가 돌려준 값)의 excess risk는 $$R(\tilde f)-R^\ast=\underbrace{R(f_{\mathcal F})-R^\ast}_{\text{approximation}}+\underbrace{R(\hat f)-R(f_{\mathcal F})}_{\text{estimation}}+\underbrace{R(\tilde f)-R(\hat f)}_{\text{optimization}}$$ 로 분해된다. Approximation error는 Chapter 2의 universal approximation이, optimization error는 Chapter 4가 다룬 문제이다. 이 장의 주제는 가운데의 estimation error, 즉 유한한 sample로 학습한 대가이다. 고전적인 직관은 $\mathcal F$가 클수록 approximation error는 줄고 estimation error는 커진다는 것이다(Chapter 1의 bias–variance trade-off).
5.2Uniform convergence와 그 한계
고정된 $f$ 하나에 대해서는 law of large numbers로 $\hat R_n(f)\to R(f)$이다. 그러나 $\hat f$는 data를 보고 고른 것이므로 data와 독립이 아니다. 그래서 class 전체에서 동시에 $\hat R_n$이 $R$에 가깝다는 uniform convergence가 필요하다.
$\ell\in[0,1]$이고 $|\mathcal F|\lt\infty$이면, 확률 $1-\delta$ 이상으로 모든 $f\in\mathcal F$에 대해 동시에 $$\big|R(f)-\hat R_n(f)\big|\le\varepsilon_n:=\sqrt{\frac{\log|\mathcal F|+\log(2/\delta)}{2n}}.$$ 따라서 같은 사건 위에서 $R(\hat f)\le R(f_{\mathcal F})+2\varepsilon_n$이다.
고정된 $f$에 대해 $\ell(f(\bx_i),y_i)$는 $[0,1]$에 있는 iid 확률변수이므로 Hoeffding's inequality로 $P(|\hat R_n(f)-R(f)|>\varepsilon)\le2e^{-2n\varepsilon^2}$. Union bound로 $P(\exists f:|\hat R_n(f)-R(f)|>\varepsilon)\le2|\mathcal F|e^{-2n\varepsilon^2}$이고, 이를 $\delta$로 두고 $\varepsilon$에 대해 풀면 $\varepsilon_n$이다. 마지막 부등식은 $R(\hat f)\le\hat R_n(\hat f)+\varepsilon_n\le\hat R_n(f_{\mathcal F})+\varepsilon_n\le R(f_{\mathcal F})+2\varepsilon_n$ (가운데는 $\hat f$가 ERM이라는 사실).
예를 들어 parameter가 $P$개이고 각각 32-bit float로 저장되는 network는 많아야 $2^{32P}$개의 서로 다른 function만 표현하는 finite class이므로 $\log|\mathcal F|\le32P\log2$이다. 이 bound는 $n\gg P$일 때만 의미가 있다. 무한 class에서는 $\log|\mathcal F|$ 자리에 class의 "크기"를 재는 다른 양이 들어간다. 대표적인 것이 Rademacher complexity $$\mathfrak R_n(\mathcal G)=\E\Big[\sup_{g\in\mathcal G}\frac1n\sum_{i=1}^n\sigma_ig(z_i)\Big],\qquad\sigma_i\iid\mathrm{Uniform}\{-1,+1\}$$ 로, class가 random한 부호 $\sigma_i$에 얼마나 잘 맞출 수 있는지를 잰다. $\mathcal G=\{(\bx,y)\mapsto\ell(f(\bx),y):f\in\mathcal F\}$, $\ell\in[0,1]$이면 확률 $1-\delta$ 이상으로 모든 $f$에 대해 $R(f)\le\hat R_n(f)+2\mathfrak R_n(\mathcal G)+\sqrt{\log(1/\delta)/(2n)}$이 성립한다(symmetrization과 McDiarmid's inequality로 증명한다). VC dimension도 같은 역할을 한다.
Zhang et al.(2017, "Understanding deep learning requires rethinking generalization")은 이 틀이 deep learning에서 무력하다는 것을 실험으로 보였다. CIFAR-10의 label을 완전히 random하게 섞어도 표준 CNN은 training accuracy 100%에 도달한다. Pixel을 random noise로 바꿔도 마찬가지이다. 즉 이 architecture의 class는 임의의 labeling을 외울 수 있으므로 Rademacher complexity가 거의 최대이고, 위의 bound는 vacuous(우변이 1 이상)하다. 그런데 같은 architecture, 같은 optimizer가 진짜 label에서는 test accuracy 90% 안팎을 낸다. Weight decay, dropout, augmentation을 모두 꺼도 일반화가 크게 무너지지 않았다.
결론은 generalization이 class $\mathcal F$의 크기만으로 결정되지 않는다는 것이다. 같은 class라도 data의 구조와 학습 algorithm이 class 안의 어느 function을 고르는지가 중요하다. 이후 절은 모두 이 "어느 function을 고르는가"를 다룬다.
5.3Double descent
고전적인 그림에서 test error는 model 복잡도에 대해 U자 모양이다. Belkin et al.(2019)은 복잡도를 training data를 정확히 맞출 수 있는 지점(interpolation threshold) 너머까지 늘리면 test error가 다시 내려간다는 것을 random feature model, 신경망, decision tree ensemble에서 관찰하고 이를 double descent라 불렀다. Nakkiran et al.(2020)은 ResNet과 Transformer에서도 width를 늘릴 때(model-wise), training epoch를 늘릴 때(epoch-wise) 같은 현상이 나타나며, threshold 근처에서는 data를 늘리는 것이 오히려 test error를 높일 수 있음(sample-wise)을 보였다. 이 현상의 핵심은 가장 단순한 model인 linear regression에서 정확히 계산된다.
Design $\bX\in\R^{n\times p}$, response $\by\in\R^n$에 대해 minimum-norm least squares estimator는 $$\hat\bbeta=\bX^+\by,$$ $\bX^+$는 Moore–Penrose pseudoinverse이다. $p\lt n$이고 $\bX$가 full column rank이면 OLS $(\bX^\top\bX)^{-1}\bX^\top\by$와 같고, $p>n$이고 $\bX$가 full row rank이면 $\bX^+=\bX^\top(\bX\bX^\top)^{-1}$로서 $\bX\hat\bbeta=\by$를 만족하는(interpolate하는) 모든 해 중 $\|\hat\bbeta\|_2$가 가장 작은 것이다.
다음 설정을 생각한다. $\bx\sim\N(\mathbf 0,\bI_p)$, $y=\bx^\top\bbeta+\epsilon$, $\epsilon\sim\N(0,\sigma^2)$, $\|\bbeta\|=r$이고, $\bX$의 row는 iid이다. 새 data $\bx$에서의 excess risk는 $\E_\bx[(\bx^\top\hat\bbeta-\bx^\top\bbeta)^2]=\|\hat\bbeta-\bbeta\|^2$이다.
위 설정에서 $\bbeta$를 고정하고 $\bX,\boldsymbol\epsilon$에 대한 기댓값을 취하면
(a) $p\le n-2$일 때 $\displaystyle\E\|\hat\bbeta-\bbeta\|^2=\sigma^2\frac{p}{n-p-1}$,
(b) $p\ge n+2$일 때 $\displaystyle\E\|\hat\bbeta-\bbeta\|^2=r^2\Big(1-\frac np\Big)+\sigma^2\frac{n}{p-n-1}$,
(c) $p\in\{n-1,n,n+1\}$이면 기댓값이 발산한다.
$p,n\to\infty$, $p/n\to\gamma$이면 risk는 $\gamma\lt1$에서 $\sigma^2\gamma/(1-\gamma)$, $\gamma>1$에서 $r^2(1-1/\gamma)+\sigma^2/(\gamma-1)$로 수렴한다(Hastie et al., 2022).
(a) $\hat\bbeta=(\bX^\top\bX)^{-1}\bX^\top(\bX\bbeta+\boldsymbol\epsilon)=\bbeta+(\bX^\top\bX)^{-1}\bX^\top\boldsymbol\epsilon$이므로 $\E[\|\hat\bbeta-\bbeta\|^2\mid\bX]=\sigma^2\tr\big((\bX^\top\bX)^{-1}\big)$. $\bX^\top\bX$는 Wishart $W_p(n,\bI)$이고 inverse Wishart의 mean은 $\E[(\bX^\top\bX)^{-1}]=\bI_p/(n-p-1)$ ($n-p-1>0$)이다. Trace를 취하면 된다.
(b) $\bX$는 확률 1로 rank $n$이고 $\bP=\bX^+\bX$는 $\bX$의 row space로의 orthogonal projection이다. $\hat\bbeta-\bbeta=-(\bI-\bP)\bbeta+\bX^+\boldsymbol\epsilon$에서 첫 항은 row space에 수직이고 둘째 항은 row space 안에 있으므로 서로 직교한다. 따라서 $$\E\|\hat\bbeta-\bbeta\|^2=\E\big[\bbeta^\top(\bI-\bP)\bbeta\big]+\sigma^2\E\tr\big(\bX^{+}\bX^{+\top}\big).$$ Orthogonal 행렬 $\mathbf O$에 대해 $\bX\mathbf O$와 $\bX$는 분포가 같으므로 $\E\bP$는 모든 $\mathbf O$와 교환되고, 따라서 $\E\bP=c\bI$이다. $\tr\bP=n$에서 $c=n/p$. 둘째 항은 $\tr(\bX^+\bX^{+\top})=\tr\big((\bX\bX^\top)^{-1}\big)$이고 $\bX\bX^\top\sim W_n(p,\bI)$이므로 기댓값이 $n/(p-n-1)$이다.
(c) $W_p(m,\bI)$의 inverse는 $m\ge p$이면 확률 1로 존재하지만 그 mean은 $m>p+1$일 때만 유한하다. $p=n-1$이면 $W_p(n,\bI)$에서 $n=p+1$, $p=n+1$이면 $W_n(p,\bI)$에서 $p=n+1$이 경계이고, $p=n$이면 $W_n(n,\bI)$로 조건을 만족하지 않는다. 어느 경우든 $\E\tr(\cdot)^{-1}=\infty$이다. 극한은 (a), (b)에서 바로 나온다.
이 정리는 double descent의 두 원인을 분리해 보여 준다.
- Threshold에서의 폭발. $\gamma\to1$이면 variance가 발산한다. Marchenko–Pastur law에 따르면 $\bX^\top\bX/n$의 가장 작은 eigenvalue는 대략 $(1-\sqrt\gamma)^2$이므로, $p\approx n$에서 $\bX$는 거의 singular이고 noise $\boldsymbol\epsilon$이 그 방향으로 엄청나게 증폭된다. Interpolate해야 하는데 자유도가 딱 맞아서, noise까지 맞추려면 계수가 아주 커져야 하는 것이다.
- Threshold 너머의 하강. $\gamma>1$이면 interpolating 해가 무수히 많고, min-norm 해는 그중 noise를 가장 "얇게 펴서" 맞추는 것이다. Variance $\sigma^2/(\gamma-1)$는 $\gamma$가 커질수록 줄어든다. 대신 $\bbeta$ 중 row space 밖의 성분을 못 보는 bias $r^2(1-1/\gamma)$가 늘어난다.
위 정리에서는 $p$가 바뀔 때 true model 자체가 바뀐다. 같은 문제에 대해 model 크기만 바꾸려면, 전체 $D$개의 feature 중 앞의 $p$개만 쓰는 misspecified model을 생각하면 된다. Feature가 isotropic이면 쓰지 않은 $D-p$개 feature의 기여 $\sum_{j>p}x_j\beta_j$는 사용한 feature와 독립인 Gaussian noise와 같으므로, $\sigma^2$를 $\sigma^2_{\text{eff}}=\sigma^2+\sum_{j>p}\beta_j^2$로, $r^2$을 $\sum_{j\le p}\beta_j^2$로 바꾸면 정리를 그대로 쓸 수 있다. Test MSE는 여기에 $\sigma^2_{\text{eff}}$를 더한 것이다.
(b)는 Bartlett et al.(2020)의 benign overfitting을 보여 준다. Covariance의 spectrum이 소수의 큰 eigenvalue(신호)와 많은 작은 eigenvalue(noise를 흡수할 공간)로 나뉘어 있으면, noise까지 외운 interpolator도 거의 최적의 test 성능을 낸다. 실제 data(image, text)의 feature spectrum은 대개 이런 빠르게 감소하는 모양이다.
정리하면 double descent는 "parameter가 많을수록 좋다"는 법칙이 아니다. (1) $p\approx n$에서 regularization 없이 interpolate하는 것은 위험하고, (2) 그 너머에서는 무수한 interpolator 중 어느 것을 고르느냐가 성능을 결정하며, (3) 적절히 regularize하면 peak는 사라진다(Nakkiran et al., 2021). (2)에서 "어느 것을 고르느냐"를 명시적인 penalty 없이 결정하는 것이 optimizer이다.
5.4Implicit regularization
Over-parameterized model에서 training loss를 0으로 만드는 $\theta$는 하나가 아니라 manifold를 이룬다. 그중 어디에 도착하는지는 loss가 아니라 initialization과 optimizer가 정한다. 이처럼 algorithm 자체가 특정 해를 선호하는 것을 implicit regularization(implicit bias)이라 한다. Linear regression에서는 이것이 정확히 계산된다.
$p>n$, $\mathrm{rank}(\bX)=n$인 $\L(\btheta)=\frac12\|\bX\btheta-\by\|^2$에 gradient descent $\btheta_{t+1}=\btheta_t-\eta\bX^\top(\bX\btheta_t-\by)$를 $\btheta_0=\mathbf 0$, $0\lt\eta\lt2/s_{\max}^2$($s_{\max}$는 $\bX$의 최대 singular value)로 적용하면 $\btheta_t\to\bX^+\by$이다. 일반적인 $\btheta_0$에서는 $\btheta_t\to\bX^+\by+(\bI-\bP)\btheta_0$, $\bP=\bX^+\bX$이다.
$\bX=\sum_{i=1}^ns_i\bu_i\bv_i^\top$(SVD, $s_i>0$)로 쓰고 $\btheta$를 $\bv_i$ 방향 성분 $c_i=\bv_i^\top\btheta$와 null space 성분으로 나눈다. Gradient $\bX^\top(\bX\btheta-\by)=\sum_is_i\bv_i(s_ic_i-\bu_i^\top\by)$는 row space 안에 있으므로 null space 성분은 $\btheta_0$의 것 $(\bI-\bP)\btheta_0$에서 변하지 않는다. Row space 성분은 $$c_i^{(t+1)}-\frac{\bu_i^\top\by}{s_i}=(1-\eta s_i^2)\Big(c_i^{(t)}-\frac{\bu_i^\top\by}{s_i}\Big)$$ 이고 $|1-\eta s_i^2|\lt1$이므로 $c_i^{(t)}\to\bu_i^\top\by/s_i$. 극한 $\sum_i(\bu_i^\top\by/s_i)\bv_i$가 바로 $\bX^+\by$이다. 모든 interpolator는 $\bX^+\by+\bv$ ($\bv\in\mathrm{null}(\bX)$)의 꼴이고 $\|\bX^+\by+\bv\|^2=\|\bX^+\by\|^2+\|\bv\|^2$이므로 $\bX^+\by$가 norm이 가장 작다.
즉 0에서 출발한 gradient descent는 penalty 없이도 앞 절의 min-norm 해를 고른다. Initialization이 크면 그 null space 성분이 그대로 남으므로 결과가 달라진다. Deep network에서 작은 initialization이 일반화에 유리하다는 경험과도 맞는다.
증명에서 얻은 식은 학습을 중간에 멈춘 경우도 알려 준다. $\btheta_0=\mathbf 0$이면 $$\btheta_t=\sum_{i=1}^n\underbrace{\big[1-(1-\eta s_i^2)^t\big]}_{\text{GD filter}}\frac{\bu_i^\top\by}{s_i}\bv_i,\qquad\hat\btheta_\lambda^{\text{ridge}}=\sum_{i=1}^n\underbrace{\frac{s_i^2}{s_i^2+\lambda}}_{\text{ridge filter}}\frac{\bu_i^\top\by}{s_i}\bv_i.$$ 둘 다 singular value가 큰 방향(신호가 강한 방향)은 거의 그대로 두고, 작은 방향(noise가 증폭되는 방향)은 0 쪽으로 줄인다. $\eta s^2$이 작을 때 $1-(1-\eta s^2)^t\approx1-e^{-\eta ts^2}$이고, 이는 $s^2\ll1/(\eta t)$에서 $\approx\eta ts^2$, $s^2\gg1/(\eta t)$에서 $\approx1$로 ridge filter와 같은 모양이다. 그래서 early stopping은 $\lambda\approx1/(\eta t)$인 ridge와 근사적으로 같다. Chapter 4에서 "early stopping은 L2 regularization과 비슷하다"고 한 것의 정확한 의미가 이것이다.
Classification에서는 implicit bias가 더 극적이다. Linearly separable data에 logistic loss로 gradient descent를 하면 loss를 0으로 보내기 위해 $\|\bw_t\|\to\infty$가 되는데, 그 방향은 특정한 해로 수렴한다.
$\{(\bx_i,y_i)\}$, $y_i\in\{\pm1\}$이 linearly separable이고 충분히 작은 $\eta$로 logistic loss $\sum_i\log(1+e^{-y_i\bw^\top\bx_i})$에 gradient descent를 하면 $$\frac{\bw_t}{\|\bw_t\|}\to\frac{\hat\bw}{\|\hat\bw\|},\qquad\hat\bw=\argmin_\bw\|\bw\|^2\ \ \text{s.t.}\ \ y_i\bw^\top\bx_i\ge1\ \ \forall i,$$ 즉 hard-margin SVM의 방향으로 수렴하며, 그 속도는 $O(1/\log t)$이다.
Training accuracy가 100%가 된 뒤에도 계속 학습하면 margin이 천천히 커지면서 test 성능이 좋아질 수 있다는 뜻이다. 수렴이 $1/\log t$로 매우 느리다는 것도 실용적인 의미가 있다. Homogeneous deep network(예: bias 없는 ReLU network)에서도 gradient flow가 margin maximization 문제의 KKT point 방향으로 수렴한다는 결과가 있다(Lyu & Li, 2020). Matrix factorization $\bW=\mathbf U\mathbf V^\top$를 gradient descent로 학습하면 작은 nuclear norm(low rank) 해를 선호한다는 결과와 추측도 같은 맥락이다(Gunasekar et al., 2017).
5.5Sharpness, flat minima, SGD
Minimum 근처에서의 loss의 곡률을 sharpness라 하고, 보통 Hessian의 최대 eigenvalue $\lambda_{\max}(\nabla^2\L(\theta^\ast))$로 잰다. 오래된 가설(Hochreiter & Schmidhuber, 1997)은 평평한(flat) minimum이 일반화를 잘한다는 것이다. Training data에서 계산한 loss surface와 test data의 loss surface는 조금 어긋나 있는데, 평평한 곳에서는 그 어긋남이 loss를 크게 바꾸지 않기 때문이다.
Optimizer는 이 선호를 자연스럽게 가진다. Minimum $\theta^\ast$ 근처에서 $\L\approx\L^\ast+\frac12(\theta-\theta^\ast)^\top\mathbf H(\theta-\theta^\ast)$이면 gradient descent는 $\theta_{t+1}-\theta^\ast=(\bI-\eta\mathbf H)(\theta_t-\theta^\ast)$이고, 이것이 수렴하려면 $\lambda_{\max}(\mathbf H)\lt2/\eta$이어야 한다(Chapter 4의 descent lemma 조건 $\eta\lt2/\beta$와 같다). 따라서 learning rate $\eta$로는 sharpness가 $2/\eta$보다 큰 minimum에 머무를 수 없다. 큰 learning rate는 평평한 minimum만 허용하는 implicit regularization이다. Cohen et al.(2021)은 실제 network를 full-batch GD로 학습하면 sharpness가 학습 중 증가하다가 $2/\eta$ 근처에서 멈추고 그 경계를 따라 학습이 진행됨(edge of stability)을 관찰했다.
SGD의 noise도 같은 방향으로 작용한다. Mini-batch gradient는 full gradient에 평균 0, covariance가 대략 $\bSigma(\theta)/B$인 noise가 더해진 것이다($\bSigma$는 sample별 gradient의 covariance). 작은 $\eta$에서 SGD를 SDE $\dd\theta=-\nabla\L\,\dd t+\sqrt{\eta/B}\,\bSigma^{1/2}\dd\mathbf B_t$로 근사하면 noise의 크기("temperature")는 $\eta/B$로 결정된다. 이 관점에서 batch를 $k$배로 키우면 learning rate도 $k$배로 키워야 같은 dynamics가 유지된다는 linear scaling rule(Goyal et al., 2017)이 나온다. Keskar et al.(2017)은 large-batch 학습이 sharp minimum에 도달하고 일반화가 나쁜 경향을 보고했다.
주의할 점도 있다. ReLU network에서 한 layer의 weight를 $\alpha$배, 다음 layer를 $1/\alpha$배 하면 function은 그대로인데 Hessian은 임의로 커지거나 작아진다(Dinh et al., 2017). 즉 sharpness는 parameterization에 의존하므로 그 자체로 일반화의 척도는 아니다. 이 문제를 parameterization에 덜 민감하게 다루는 틀이 PAC-Bayes이다.
$\ell\in[0,1]$, data를 보기 전에 정한 prior $P$(parameter 위의 distribution)에 대해, 확률 $1-\delta$ 이상으로 모든 posterior $Q$에 대해 동시에 $$\E_{\theta\sim Q}R(f_\theta)\le\E_{\theta\sim Q}\hat R_n(f_\theta)+\sqrt{\frac{\KL(Q\|P)+\log(2\sqrt n/\delta)}{2n}}.$$
Bound는 parameter 수가 아니라 data가 prior에서 얼마나 정보를 더했는지($\KL(Q\|P)$)에 의존한다. 학습한 $\hat\theta$ 주위에 $Q=\N(\hat\theta,s^2\bI)$를 두면, minimum이 평평할수록 큰 $s$를 써도 $\E_Q\hat R_n$이 작게 유지되고, $s$가 클수록 prior $\N(\mathbf 0,s_0^2\bI)$와의 KL(Proposition 3.6)이 작아진다. Flat minimum은 "적은 정보로 기술되는 해"라는 뜻이 된다. Dziugaite & Roy(2017)는 이 bound의 우변을 직접 최적화해 MNIST에서 parameter가 data보다 많은 network에 대해 처음으로 non-vacuous한 bound를 얻었다.
이 아이디어를 optimizer에 직접 넣은 것이 sharpness-aware minimization(SAM; Foret et al., 2021)이다. $$\min_\theta\max_{\|\boldsymbol\varepsilon\|\le\rho}\L(\theta+\boldsymbol\varepsilon),\qquad\hat{\boldsymbol\varepsilon}=\rho\frac{\nabla\L(\theta)}{\|\nabla\L(\theta)\|},\qquad\theta\leftarrow\theta-\eta\nabla\L(\theta+\hat{\boldsymbol\varepsilon}).$$ 안쪽 max를 1차 Taylor 근사로 풀면 gradient 방향으로 $\rho$만큼 이동한 점이 최악의 점이다. 주변에서 가장 나쁜 loss를 줄이므로 평평한 영역을 찾는다. Gradient를 두 번 계산하므로 비용은 약 두 배이다.
5.6Neural tangent kernel
Width가 매우 큰 network에서는 학습 중 각 weight가 아주 조금만 움직인다. 그렇다면 initialization $\theta_0$ 주위의 1차 Taylor 근사 $$f(\bx;\theta)\approx f_{\text{lin}}(\bx;\theta)=f(\bx;\theta_0)+\nabla_\theta f(\bx;\theta_0)^\top(\theta-\theta_0)$$ 가 학습 전체에서 유효할 수 있다. $f_{\text{lin}}$은 $\theta$에 대해 linear이고 $\bx$에 대해서는 non-linear인, feature map $\boldsymbol\phi(\bx)=\nabla_\theta f(\bx;\theta_0)$를 쓰는 linear model이다. 이 feature의 inner product $$\Theta(\bx,\bx')=\nabla_\theta f(\bx;\theta_0)^\top\nabla_\theta f(\bx';\theta_0)$$ 를 neural tangent kernel(NTK)이라 한다.
Training data $\bX=\{\bx_i\}_{i=1}^n$에서 MSE $\L=\frac12\sum_i(f(\bx_i)-y_i)^2$에 gradient flow $\dot\theta=-\nabla_\theta\L$를 적용하면, 임의의 $\bx$에서 $$\frac{\dd}{\dd t}f_t(\bx)=-\sum_{i=1}^n\Theta_t(\bx,\bx_i)\big(f_t(\bx_i)-y_i\big).$$ Kernel이 상수 $\Theta$이고 $n\times n$ 행렬 $\Theta(\bX,\bX)$가 positive definite이면, $\mathbf u_t=f_t(\bX)$에 대해 $$\mathbf u_t=\by+e^{-\Theta(\bX,\bX)t}(\mathbf u_0-\by),\qquad f_t(\bx)=f_0(\bx)+\Theta(\bx,\bX)\Theta(\bX,\bX)^{-1}\big(\bI-e^{-\Theta(\bX,\bX)t}\big)(\by-\mathbf u_0).$$
Chain rule로 $\frac{\dd}{\dd t}f_t(\bx)=\nabla_\theta f(\bx;\theta_t)^\top\dot\theta$이고 $\dot\theta=-\sum_i\nabla_\theta f(\bx_i;\theta_t)(f_t(\bx_i)-y_i)$를 넣으면 첫 식이다. $\bx=\bx_i$들에 대해 모으면 linear ODE $\dot{\mathbf u}=-\Theta(\bX,\bX)(\mathbf u-\by)$이고 해는 $\mathbf u_t-\by=e^{-\Theta t}(\mathbf u_0-\by)$이다. 이를 첫 식에 넣고 $0$부터 $t$까지 적분하면 $f_t(\bx)-f_0(\bx)=-\Theta(\bx,\bX)\int_0^te^{-\Theta s}\dd s\,(\mathbf u_0-\by)=\Theta(\bx,\bX)\Theta^{-1}(\bI-e^{-\Theta t})(\by-\mathbf u_0)$.
Jacot et al.(2018)은 적절한 scaling(NTK parameterization)에서 width $\to\infty$이면 initialization의 $\Theta_0$가 deterministic한 kernel로 수렴하고 학습 중에도 변하지 않음을 보였다. 그러면 위 정리가 정확히 적용되어 다음이 따른다.
- Global convergence. $\Theta(\bX,\bX)\succ0$이면 training error가 $e^{-\lambda_{\min}t}$로 0에 수렴한다. Non-convex임에도 over-parameterized network가 training loss를 0으로 만드는 이유에 대한 한 가지 설명이다(Du et al., 2019).
- Kernel regression. $t\to\infty$에서 $f_\infty(\bx)=f_0(\bx)+\Theta(\bx,\bX)\Theta(\bX,\bX)^{-1}(\by-\mathbf u_0)$로, NTK를 쓰는 kernel ridgeless regression이다. 앞 절의 min-norm 결과는 model이 처음부터 linear인 특수한 경우이다. 일반화는 kernel의 성질(어떤 function을 smooth하다고 보는가)로 분석할 수 있다.
- Spectral bias. 오차는 $\Theta(\bX,\bX)$의 eigenvector 방향마다 $e^{-\lambda_kt}$로 줄어든다. Eigenvalue가 큰 방향(대개 저주파의 매끄러운 function)을 먼저 배우고 고주파 세부와 noise는 나중에 배운다. Early stopping이 효과적인 이유이기도 하다.
한계도 분명하다. Kernel이 고정되어 있다는 것은 학습 중 feature $\boldsymbol\phi(\bx)$가 바뀌지 않는다는 뜻이고, 이 regime을 lazy training이라 한다(Chizat et al., 2019). 그러나 Chapter 12에서 볼 transfer learning의 성공은 network가 학습 중에 data에 맞는 feature를 만든다는 데 있다. 실제로 유한한 width의 network는 대응하는 NTK kernel regression보다 성능이 좋다. Feature learning이 일어나는 regime을 다루는 mean-field 이론과 μP(maximal update parameterization; Yang & Hu, 2021)가 이 차이를 다룬다. μP는 width를 바꿔도 최적 learning rate 같은 hyperparameter가 유지되도록 하는 parameterization으로, 큰 model의 hyperparameter를 작은 model에서 고르는 데 쓰인다.
5.7정리: 무엇이 일반화를 결정하는가
현재까지의 이해를 통계학의 언어로 요약하면 다음과 같다.
- Parameter 수는 좋은 복잡도 척도가 아니다. 같은 class 안에서 algorithm이 고른 해의 norm, margin, sharpness, 또는 prior로부터의 KL 같은 data 의존적인 양이 일반화와 관련된다.
- Over-parameterization은 interpolating 해를 많이 만들고, optimizer(작은 initialization, gradient descent, 큰 learning rate, SGD noise)가 그중 단순한 해를 고른다. 명시적 regularization(weight decay, dropout)은 이 선택을 보강한다.
- Interpolation이 해롭지 않으려면 data에 구조가 있어야 한다. 소수의 방향에 신호가 모여 있고 나머지 방향이 noise를 흡수할 수 있을 때 benign overfitting이 일어난다.
- Interpolation threshold 근처는 위험하다. Label noise가 있는 data에서 model 크기나 학습 시간을 바꿀 때 test error가 일시적으로 나빠질 수 있으며, 적절한 regularization과 early stopping이 이를 완화한다.
실무에서 일반화를 판단하는 최종 근거는 여전히 held-out data에서의 성능이다. 그 측정을 통계적으로 올바르게 하는 방법은 Chapter 22에서, 예측의 불확실성을 정량화하는 방법은 Chapter 21에서 다룬다.
Architectures
Chapter 6Convolutional Neural Network
Lecture Week 01 (3.1), Week 03 (Week 2 slides)
MLP는 input의 구조를 전혀 가정하지 않는다. Image의 pixel을 한 줄로 펴서 넣으면 "가까운 pixel끼리 관련이 깊다"는 정보가 사라진다. Convolutional neural network(CNN)는 locality와 weight sharing이라는 가정을 구조에 넣어 parameter를 크게 줄이면서 spatial information을 이용한다. 이 장에서는 convolution을 정확히 정의하고, 그 성질과 대표 architecture, 그리고 classification·segmentation·detection으로의 확장을 다룬다.
6.1Data는 tensor이다
Deep learning에서 다루는 data는 모두 다차원 배열, 즉 tensor로 표현된다. 차원 수는 batch 축을 제외하고 센다.
| Domain | Shape | 예 |
|---|---|---|
| Tabular | $(d)$ | 나이, 키, 검사 수치 같은 feature vector |
| Signal / time series | $(C, T)$ | Channel $C$개, 길이 $T$인 sensor 신호 |
| Text | $(n, d)$ | Token $n$개 각각의 $d$차원 embedding |
| Image | $(C, H, W)$ | RGB이면 $C=3$, MNIST는 $(1,28,28)$ |
| Video | $(T, C, H, W)$ | Frame $T$개 |
Grayscale image는 각 pixel 값이 밝기(보통 0–255)를 뜻하는 숫자 행렬이므로 바로 연산할 수 있다. 문제는 이것을 어떤 구조의 function에 넣느냐이다.
6.2MLP의 한계
$224\times224\times3$ image를 flatten하면 150,528차원이다. 첫 hidden layer의 width가 1,000이면 그 layer 하나에만 약 $1.5\times10^8$개의 weight가 필요하다. 더 근본적인 문제는 flatten 순간 pixel 사이의 이웃 관계가 사라진다는 것이다. Image를 한 pixel 옆으로 옮기면 사람에게는 같은 그림이지만 MLP에게는 완전히 다른 input vector가 된다.
물론 MLP는 regression과 달리 "input의 몇 번째 자리에 어떤 feature가 와야 한다"는 제약이 없어 raw pixel에서 직접 학습할 수 있다. 하지만 image가 가진 spatial 구조를 활용하지 못하므로 비효율적이다. CNN은 image를 2차원(channel까지 3차원) 그대로 받아 이 구조를 이용한다.
6.3Convolution의 정의
Input $X\in\R^{H\times W}$, kernel(filter) $K\in\R^{k\times k}$에 대해 $$(X\star K)[i,j]=\sum_{u=0}^{k-1}\sum_{v=0}^{k-1}X[i+u,\,j+v]\;K[u,v].$$
수학에서의 convolution은 $\sum X[i-u,j-v]K[u,v]$로 kernel을 뒤집지만, deep learning library는 위의 cross-correlation을 구현하고 관습적으로 convolution이라 부른다. $K$가 학습되는 parameter이므로 뒤집힌 kernel을 배울 뿐 표현력에는 차이가 없다.
Convolution은 linear map이므로 행렬로 쓸 수 있다. 1차원 input $\bx\in\R^5$와 kernel $(k_0,k_1,k_2)$의 convolution(stride 1, padding 0)은 $$\begin{pmatrix}y_0\\y_1\\y_2\end{pmatrix}=\begin{pmatrix}k_0&k_1&k_2&0&0\\0&k_0&k_1&k_2&0\\0&0&k_0&k_1&k_2\end{pmatrix}\begin{pmatrix}x_0\\\vdots\\x_4\end{pmatrix}$$ 이다. 즉 convolution layer는 (1) 대부분의 원소가 0이고(locality), (2) 모든 row가 같은 값을 한 칸씩 밀어 쓴(weight sharing) 특수한 구조의 fully-connected layer이다. 이런 행렬을 Toeplitz matrix라 하며, 2차원에서는 doubly block Toeplitz가 된다. Backpropagation에서 input에 대한 gradient는 이 행렬의 transpose를 곱하는 것이고, segmentation의 upsampling에 쓰는 transposed convolution이 바로 이 $M^\top$ 연산이다.
실제 구현에서는 반대로, input에서 kernel이 닿는 $k\times k\times C_{\text{in}}$ patch들을 펼쳐 행렬의 column으로 늘어놓고(im2col) kernel 행렬 $C_{\text{out}}\times(C_{\text{in}}k^2)$과 한 번에 곱한다. Convolution을 GPU가 가장 잘하는 큰 행렬 곱 하나로 바꾸는 방법이다.
실제 layer는 여러 channel을 다룬다. Input $X\in\R^{C_{\text{in}}\times H\times W}$, kernel $K\in\R^{C_{\text{out}}\times C_{\text{in}}\times k\times k}$, bias $b\in\R^{C_{\text{out}}}$, stride $s$, padding $p$에 대해 $$Y[o,i,j]=b_o+\sum_{c=1}^{C_{\text{in}}}\sum_{u,v}K[o,c,u,v]\;\tilde X[c,\,si+u,\,sj+v],$$ 여기서 $\tilde X$는 가장자리에 $p$개씩 0을 덧댄 input이다. 각 output channel $o$는 모든 input channel을 보는 별도의 filter를 가진다. 서로 다른 filter는 서로 다른 pattern(edge 방향, 질감 등)에 반응하도록 학습된다. 같은 input을 여러 개의 filter로 본다는 뜻이다.
| Hyperparameter | 의미 |
|---|---|
in_channels | Input의 channel 수 $C_{\text{in}}$ |
out_channels | Filter 개수 = output channel 수 $C_{\text{out}}$ |
kernel_size | Filter의 공간 크기 $k\times k$ |
stride | Filter가 한 번에 이동하는 칸 수 $s$ |
padding | Input 가장자리에 덧대는 칸 수 $p$ |
dilation | Kernel 원소 사이 간격 $d$. 유효 kernel 크기는 $d(k-1)+1$ |
(a) $H_{\text{out}}=\Big\lfloor\dfrac{H+2p-d(k-1)-1}{s}\Big\rfloor+1$, $W_{\text{out}}$도 같다. ($d=1$이면 $\lfloor(H+2p-k)/s\rfloor+1$.)
(b) Parameter 수 $=C_{\text{out}}(C_{\text{in}}k^2+1)$. Input의 공간 크기 $H,W$와 무관하다.
(c) Multiply–accumulate 연산 수 $=C_{\text{out}}H_{\text{out}}W_{\text{out}}\cdot C_{\text{in}}k^2$.
예를 들어 $3\times224\times224$ input에 $3\times3$ filter 64개($p=1,s=1$)를 쓰면 output은 $64\times224\times224$이고 parameter는 $64\cdot(27+1)=1{,}792$개뿐이다. 같은 크기의 output을 MLP로 만들려면 $150{,}528\times3{,}211{,}264$개가 필요하다. $k=3,p=1,s=1$이면 크기가 유지되므로 "same" padding이라 부른다.
6.4Inductive bias: locality, weight sharing, equivariance
Convolution이 효율적인 이유는 두 가지 가정 때문이다.
- Locality: output의 한 위치는 input의 작은 이웃($k\times k$)에만 의존한다.
- Weight sharing: 모든 위치에 같은 filter를 쓴다. 위치마다 다른 weight를 쓰지 않는다.
Model 구조에 넣은 이런 가정을 inductive bias라 한다. 가정이 data와 맞으면 적은 data로도 잘 학습되고, 틀리면 표현력을 제한한다. Weight sharing에서 다음 성질이 나온다.
Shift operator $(T_\delta X)[i,j]=X[i-\delta_1,j-\delta_2]$에 대해 stride 1 convolution은 (경계 효과를 무시하면) $$(T_\delta X)\star K=T_\delta(X\star K).$$
$((T_\delta X)\star K)[i,j]=\sum_{u,v}X[i+u-\delta_1,j+v-\delta_2]K[u,v]=(X\star K)[i-\delta_1,j-\delta_2]$.
즉 input이 이동하면 feature map도 같은 만큼 이동한다(equivariance). 고양이가 image 어디에 있든 같은 filter가 같은 반응을 만든다. Classification에서는 위치와 무관한 결론이 필요하므로, 마지막에 공간 축을 pooling으로 요약해 근사적인 invariance를 얻는다. Stride가 1보다 크거나 pooling이 끼면 equivariance는 정확히 성립하지 않는다.
고전 image processing의 filter도 같은 연산이다. 예를 들어 $$K_{\text{edge}}=\begin{pmatrix}-1&-1&-1\\-1&8&-1\\-1&-1&-1\end{pmatrix},\qquad K_{\text{sharpen}}=\begin{pmatrix}0&-1&0\\-1&5&-1\\0&-1&0\end{pmatrix}$$ 에서 edge kernel은 원소의 합이 0이므로 밝기가 균일한 영역에서는 0을 내고 밝기가 급변하는 경계에서만 큰 값을 낸다. Sharpen kernel은 합이 1이라 평균 밝기는 유지하면서 중심과 주변의 차이를 키운다. CNN은 이런 kernel을 사람이 정하지 않고 data로 학습한다.
초기 CNN 설명에서는 "filter가 edge detector 역할을 한다"는 해석을 많이 했다. 실제로 첫 layer filter는 Gabor filter 비슷한 edge·색 detector로 학습되지만, 깊은 layer의 filter를 사람이 해석하기는 어렵다. 지금은 "CNN은 spatial information을 이용하고 MLP는 그러지 못한다" 정도로 이해하면 충분하다.
그래도 대략적인 위계는 관찰된다. 앞쪽 layer는 edge와 색 같은 low-level feature, 중간 layer는 질감과 부분 형태 같은 mid-level feature, 뒤쪽 layer는 물체의 부분이나 전체에 반응하는 high-level feature를 표현한다(feature hierarchy).
Receptive field
Output 한 위치가 의존하는 input 영역의 크기를 receptive field라 한다. Layer $l$의 kernel 크기를 $k_l$, stride를 $s_l$이라 하면 receptive field의 한 변 길이 $r_l$은 $$r_0=1,\qquad r_l=r_{l-1}+(k_l-1)\prod_{i=1}^{l-1}s_i$$ 로 커진다. Stride 1인 $3\times3$ convolution을 $L$번 쌓으면 $r_L=2L+1$이다. 중간에 stride 2 layer가 있으면 그 뒤의 layer는 한 칸이 input의 2칸에 해당하므로 receptive field가 두 배 속도로 커진다. 깊은 layer일수록 넓은 영역을 보므로 더 큰 구조(물체의 부분, 물체 전체)를 표현할 수 있다.
6.5Pooling과 1×1 convolution
Pooling은 parameter 없이 공간 크기를 줄이는 연산이다. Max pooling은 window 안의 최댓값, average pooling은 평균을 취한다. 출력 크기는 convolution과 같은 공식을 따른다. 흔한 설계는 convolution은 크기를 유지하고($p=1,s=1$) pooling이나 stride 2 convolution으로 크기를 절반씩 줄이는 것이다.
Global average pooling(GAP)은 각 channel의 feature map 전체를 평균해 $C\times H\times W$를 $C$차원 vector로 만든다. $$h_c=\frac{1}{HW}\sum_{i,j}A[c,i,j].$$ Input 해상도와 무관하게 고정 길이 vector를 주므로 classifier 앞에서 가장 많이 쓰이고(shape을 신경 쓰지 않아도 된다), Chapter 13의 CAM도 이 구조를 이용한다. GAP는 공간 위치에 대해 정확히 invariant하므로, translation equivariant한 convolution layer 뒤에 두면 network 전체가 (경계와 stride 효과를 제외하면) translation invariant가 된다. Max pooling은 window 안에서 최댓값의 위치가 조금 바뀌어도 같은 output을 주므로 작은 이동에 대한 국소적 invariance를 준다.
$1\times1$ convolution은 공간적으로는 아무것도 섞지 않고 각 pixel 위치에서 channel 방향으로 linear map $\R^{C_{\text{in}}}\to\R^{C_{\text{out}}}$을 적용한다. Channel 수를 줄이거나 늘리는 데 쓰이며, pixel마다 같은 MLP layer를 적용하는 것과 같다. Parameter는 $C_{\text{out}}(C_{\text{in}}+1)$개이다.
$1\times1$ convolution은 경량 CNN의 핵심 부품이기도 하다. Depthwise separable convolution(MobileNet)은 일반 convolution을 (1) channel마다 따로 적용하는 $k\times k$ depthwise convolution과 (2) channel을 섞는 $1\times1$ pointwise convolution으로 나눈다. Bias를 빼고 parameter 수를 비교하면 $$\underbrace{C_{\text{in}}C_{\text{out}}k^2}_{\text{standard}}\quad\text{vs.}\quad\underbrace{C_{\text{in}}k^2+C_{\text{in}}C_{\text{out}}}_{\text{separable}},$$ 비율은 $\frac1{C_{\text{out}}}+\frac1{k^2}$이다. $k=3$, $C_{\text{out}}=256$이면 약 1/8.7로 줄어든다. 공간 방향의 처리와 channel 방향의 처리를 분리할 수 있다는 가정이 들어간 것이다.
6.6CNN architectures
CNN의 역사는 짧게 정리하면 다음과 같다. LeNet-5(LeCun et al., 1998)가 손글씨 숫자 인식에서 convolution–pooling–fully connected 구조를 확립했고, AlexNet(Krizhevsky et al., 2012)이 ReLU, dropout, GPU 학습으로 ImageNet 대회(ILSVRC)를 큰 차이로 우승하며 deep learning 붐을 일으켰다. 이후 VGG(2014), GoogLeNet/Inception(2014, 여러 크기의 kernel과 $1\times1$ convolution을 병렬로 쓰는 inception module), ResNet(2015)이 이어졌고, EfficientNet(2019)은 depth, width, 해상도를 하나의 계수로 함께 키우는 compound scaling을 제안했다.
VGG
VGG(Simonyan & Zisserman, 2014)는 $3\times3$ convolution(stride 1, padding 1)만 깊게 쌓고 $2\times2$ max pooling으로 해상도를 절반씩 줄이는 단순한 설계로 깊이의 효과를 보였다. Weight layer 수에 따라 VGG-16, VGG-19라 부르며, $224\times224\times64\to112\times112\times128\to\cdots\to7\times7\times512$로 줄인 뒤 fully connected layer 세 개(4096, 4096, 1000)와 softmax로 분류한다. $3\times3$ 두 층은 receptive field가 $5\times5$ 한 층과 같지만 parameter는 $2\cdot9C^2=18C^2$로 $25C^2$보다 적고, 사이에 non-linearity가 하나 더 들어간다. 큰 kernel 하나보다 작은 kernel 여러 개가 낫다는 것이 이후 CNN 설계의 기본이 되었다.
ResNet
층을 계속 쌓으면 성능이 좋아질 것 같지만, plain network를 20층에서 56층으로 늘리면 training error가 오히려 커진다(He et al., 2016). Test가 아니라 training error가 나빠지므로 overfitting이 아니라 optimization의 문제이며, 이를 degradation problem이라 한다. 깊은 network는 이론적으로 얕은 network를 포함한다(추가된 층이 identity를 학습하면 된다). 그런데 실제로는 여러 non-linear layer가 identity를 학습하는 것조차 어렵다.
Residual block은 output을 $\bx_{l+1}=\bx_l+F(\bx_l)$로 둔다. 학습할 대상이 전체 mapping $H(\bx)$가 아니라 identity로부터의 차이(residual) $F(\bx)=H(\bx)-\bx$이다. Identity가 최적이면 $F=0$, 즉 weight를 0 근처로 보내기만 하면 되므로 쉽다. Gradient 관점에서는 Jacobian이 $$\frac{\partial\bx_{l+1}}{\partial\bx_l}=\bI+\mathbf J_l,\qquad\mathbf J_l=\frac{\partial F}{\partial\bx_l}$$ 이다. Gradient를 row vector로 쓰면 chain rule에 의해 $$\frac{\partial\ell}{\partial\bx_l}=\frac{\partial\ell}{\partial\bx_L}\,(\bI+\mathbf J_{L-1})(\bI+\mathbf J_{L-2})\cdots(\bI+\mathbf J_l)=\frac{\partial\ell}{\partial\bx_L}\Big(\bI+\sum_{m}\mathbf J_m+\sum_{m\gt m'}\mathbf J_m\mathbf J_{m'}+\cdots\Big).$$ 전개하면 $\partial\ell/\partial\bx_L$이 아무 행렬도 곱해지지 않고 그대로 전달되는 항이 항상 포함된다. Plain network에서는 $\prod_m\mathbf J_m$ 하나뿐이어서 그 크기가 depth에 따라 지수적으로 줄어들 수 있지만, residual network에서는 그렇지 않다. 깊은 층까지 gradient가 사라지지 않는 이유이다. Shape이 바뀌는 지점에서는 shortcut에 $1\times1$ convolution(projection)을 둔다. ResNet-50 이상은 $1\times1\to3\times3\to1\times1$의 bottleneck block으로 연산량을 줄인다. Skip connection은 이후 Transformer를 포함한 거의 모든 깊은 architecture의 표준이 되었다.
6.7Tasks: classification, segmentation, detection
Classification
Image 하나에 label 하나. Encoder(convolution block들) → GAP → linear classifier → softmax의 구조이며 loss는 cross-entropy이다.
Semantic segmentation
Pixel마다 class를 예측한다. Output은 $K\times H\times W$이고 loss는 pixel별 cross-entropy의 평균이다. Encoder가 해상도를 줄였으므로 decoder에서 다시 키워야 하며, 이때 transposed convolution(학습 가능한 upsampling)이나 interpolation을 쓴다. U-Net은 encoder의 각 해상도 feature map을 decoder의 같은 해상도로 이어 붙이는(skip connection) encoder–decoder 구조로, 세밀한 경계를 복원하는 데 효과적이다. U-Net은 원래 biomedical image segmentation을 위해 제안되었고, U-Net을 중첩한 U²-Net 같은 변형도 있다. 아래 그림처럼 해상도를 줄이며 추상적인 feature를 만드는 encoder와, 해상도를 다시 키우며 skip connection으로 받은 고해상도 feature를 결합하는 decoder가 U자 모양을 이룬다. 평가에는 predicted mask $A$와 정답 $B$의 $$\text{IoU}=\frac{|A\cap B|}{|A\cup B|},\qquad\text{Dice}=\frac{2|A\cap B|}{|A|+|B|}=\frac{2\,\text{IoU}}{1+\text{IoU}}$$ 를 쓴다.
Label 자체에 위계가 있는 경우도 있다. 예를 들어 "Pets → Dogs → Poodle"처럼 상위 class와 하위 class가 tree를 이룰 때, 상위 수준의 분류를 함께 학습하거나 tree 구조를 loss에 반영하는 hierarchical classification을 쓰면 하위 class의 data가 적을 때 도움이 된다.
Object detection
Image 안의 여러 물체에 대해 bounding box $(x,y,w,h)$와 class를 예측한다. 예측 box와 정답 box의 IoU가 기준(예: 0.5) 이상이면 맞춘 것으로 본다. 같은 물체에 대한 중복 예측은 non-maximum suppression(NMS)으로 제거한다. 후보 영역을 먼저 제안하고 분류하는 two-stage 방식(R-CNN 계열)과 grid마다 box와 class를 한 번에 regression하는 one-stage 방식(YOLO, SSD)이 있으며, 평가는 class별 precision–recall curve의 면적을 평균한 mAP로 한다.
Segmentation과 detection은 architecture와 학습 trick이 빠르게 바뀌는 분야이다. 직접 설계하기보다 해당 task의 최신 SOTA 구현과 pre-trained weight를 찾아 쓰는 것을 권한다(Chapter 12).
Chapter 7Sequence Model: Embedding과 RNN
Lecture Week 05 (2. NLP Basic)
Image는 처음부터 숫자이고, 숫자의 크기에 의미가 있다(크면 밝고 작으면 어둡다). 언어는 다르다. 단어에 번호를 붙이는 것만으로는 의미가 생기지 않는다. 이 장에서는 단어를 의미 있는 vector로 바꾸는 word embedding과, 순서가 있는 data를 다루는 recurrent neural network(RNN) 계열을 정리한다. 이는 다음 장 Transformer의 배경이 된다.
7.1Text를 숫자로: token, vocabulary, one-hot
문장을 처리 단위로 쪼개는 것을 tokenization이라 한다. 단위는 단어일 수도 있고, 현대 model처럼 subword(BPE, WordPiece)일 수도 있다. 가능한 token의 집합을 vocabulary $\mathcal V$라 하고 각 token에 index를 붙인다. Token $w$의 one-hot vector $\mathbf e_w\in\{0,1\}^{|\mathcal V|}$는 $w$번째 성분만 1이다.
One-hot은 의미를 전혀 담지 못한다. 서로 다른 두 token의 one-hot은 항상 orthogonal이므로 "cat"과 "dog"의 거리나 "cat"과 "car"의 거리가 같다. 또 $|\mathcal V|$가 수만~수십만이라 매우 sparse하다.
Embedding matrix $\mathbf E\in\R^{|\mathcal V|\times d}$ ($d\ll|\mathcal V|$)에 대해 token $w$의 embedding은
$$\mathbf v_w=\mathbf E^\top\mathbf e_w,$$
즉 $\mathbf E$의 $w$번째 row이다. 실제 구현에서는 행렬 곱 없이 row를 꺼내는 lookup table(nn.Embedding)로 처리한다.
목표는 의미가 비슷한 token이 가까운 vector를 갖도록 $\mathbf E$를 학습하는 것이다. 가까움은 보통 cosine similarity로 잰다. $$\cos(\mathbf u,\mathbf v)=\frac{\mathbf u^\top\mathbf v}{\|\mathbf u\|\,\|\mathbf v\|}\in[-1,1].$$ 잘 학습된 embedding에서는 $\mathbf v_{\text{king}}-\mathbf v_{\text{man}}+\mathbf v_{\text{woman}}$과 가장 가까운 vector가 $\mathbf v_{\text{queen}}$인 것처럼 vector 연산이 의미 관계를 반영한다.
7.2word2vec: CBOW와 Skip-gram
"단어의 의미는 그 주변 단어가 결정한다"는 distributional hypothesis를 학습 objective로 만든 것이 word2vec(Mikolov et al., 2013)이다. 각 token은 center로 쓰일 때의 vector $\mathbf v_w$와 context로 쓰일 때의 vector $\mathbf u_w$를 가진다. Corpus $w_1,\dots,w_T$와 window 크기 $c$에 대해:
- Skip-gram: center로 주변을 예측한다. $$\max\;\frac1T\sum_{t=1}^T\sum_{\substack{-c\le j\le c\\ j\ne0}}\log p(w_{t+j}\mid w_t),\qquad p(o\mid c)=\frac{\exp(\mathbf u_o^\top\mathbf v_c)}{\sum_{w\in\mathcal V}\exp(\mathbf u_w^\top\mathbf v_c)}.$$
- CBOW (continuous bag of words): 주변의 평균 $\bar{\mathbf v}=\frac1{2c}\sum_{j\ne0}\mathbf v_{w_{t+j}}$로 center를 예측한다. $p(w_t\mid\text{context})=\softmax(\mathbf U\bar{\mathbf v})_{w_t}$.
둘 다 Chapter 3의 categorical cross-entropy를 minimize하는 문제이며, label은 corpus 자체에서 만들어지므로 사람이 붙인 label이 필요 없다. 이는 Chapter 12의 self-supervised learning의 원형이다.
분모의 합은 $|\mathcal V|$개 항을 계산해야 하므로 비싸다. Negative sampling은 이를 binary classification으로 바꾼다. 실제 (center, context) 쌍은 1로, noise distribution $P_n(w)\propto\text{freq}(w)^{3/4}$에서 뽑은 $K$개의 가짜 context는 0으로 분류하도록 $$\log\sigma(\mathbf u_o^\top\mathbf v_c)+\sum_{k=1}^K\E_{w_k\sim P_n}\big[\log\sigma(-\mathbf u_{w_k}^\top\mathbf v_c)\big]$$ 를 maximize한다.
Skip-gram with negative sampling의 objective는 embedding 차원이 충분히 크면 각 쌍에 대해 $$\mathbf u_c^\top\mathbf v_w=\mathrm{PMI}(w,c)-\log K,\qquad\mathrm{PMI}(w,c)=\log\frac{p(w,c)}{p(w)p(c)}$$ 에서 최적이 된다. 즉 word2vec은 shifted pointwise mutual information 행렬을 암묵적으로 factorize한다. (여기서 $P_n$은 unigram distribution으로 둔다.)
Corpus 전체 pair 수를 $|D|$, 쌍 $(w,c)$의 등장 횟수를 $\#(w,c)$, 단어 $w$의 횟수를 $\#(w)$라 하자. $x=\mathbf u_c^\top\mathbf v_w$가 다른 쌍과 독립적으로 자유롭게 정해질 수 있다고 가정하면(차원이 충분히 큼), objective 중 $x$와 관련된 부분의 기댓값은 $$J(x)=\#(w,c)\log\sigma(x)+K\,\#(w)\,P_n(c)\log\sigma(-x),\qquad P_n(c)=\frac{\#(c)}{|D|}.$$ $\sigma'(x)=\sigma(x)\sigma(-x)$를 쓰면 $J'(x)=\#(w,c)\,\sigma(-x)-K\#(w)P_n(c)\,\sigma(x)=0$에서 $e^x=\frac{\sigma(x)}{\sigma(-x)}=\frac{\#(w,c)}{K\#(w)P_n(c)}$. 따라서 $x=\log\frac{\#(w,c)\,|D|}{\#(w)\#(c)}-\log K=\widehat{\mathrm{PMI}}(w,c)-\log K$. $J$는 $x$에 대해 concave이므로 이것이 최적이다.
통계적으로 보면 word2vec은 co-occurrence 통계의 low-rank 근사이다. LSA(co-occurrence 행렬의 SVD)나 GloVe와 같은 계열에 속한다.
7.3Recurrent neural network
CNN이 공간 축에서 weight를 공유했다면 RNN은 시간 축에서 weight를 공유한다.
- MLP → CNN: spatial information을 이용하고 parameter sharing으로 계산 효율을 얻는다.
- MLP → RNN: sequential data의 temporal dependency를 학습하고 parameter sharing으로 길이와 무관한 model을 얻는다.
Input sequence $\bx_1,\dots,\bx_T$와 초기 상태 $\bh_0$에 대해 $$\bh_t=\tanh\big(\bW_{hh}\bh_{t-1}+\bW_{xh}\bx_t+\bb_h\big),\qquad \hat\by_t=\bW_{hy}\bh_t+\bb_y.$$ $\bh_t$를 hidden state라 하며 시점 $t$까지의 정보를 요약한다. 모든 시점이 같은 $\bW_{hh},\bW_{xh},\bW_{hy}$를 쓴다.
Weight가 공유되므로 train과 test의 sequence 길이가 달라도 된다. Input과 output의 형태에 따라 다섯 가지로 나눌 수 있다(Karpathy, 2015).
| 형태 | 예 |
|---|---|
| One-to-one | RNN 없는 일반 network. 고정 크기 input → 고정 크기 output (image classification) |
| One-to-many | Image 하나 → 단어 sequence (image captioning) |
| Many-to-one | 문장 → label (sentiment analysis). 마지막 $\bh_T$만 사용 |
| Many-to-many (encoder–decoder) | 문장 → 다른 길이의 문장 (machine translation, seq2seq) |
| Many-to-many (synced) | 매 시점 input에 대응하는 output (video frame별 분류, tagging) |
같은 분류를 NLP의 대표적인 task에 대응시키면 다음과 같다.
| NLP task | Input → Output |
|---|---|
| Text classification, sentiment analysis | 문장 → label |
| Machine translation | 문장 → 다른 언어의 문장 |
| Text generation (chatbot) | 앞부분 → 다음 token들 |
| Question answering, summarization | 문서 (+질문) → 답 / 요약 |
| Text similarity, plagiarism detection | 문장 쌍 → 유사도 |
7.4Backpropagation through time과 vanishing gradient
RNN을 시간 축으로 펼치면(unroll) 깊이가 $T$인 feed-forward network가 되고, 여기에 backpropagation을 적용하는 것을 backpropagation through time(BPTT)이라 한다. 시점 $t$의 loss가 시점 $k\lt t$의 hidden state에 미치는 영향은 $$\frac{\partial\bh_t}{\partial\bh_k}=\prod_{j=k+1}^{t}\frac{\partial\bh_j}{\partial\bh_{j-1}}=\prod_{j=k+1}^{t}\diag\big(\tanh'(\mathbf a_j)\big)\bW_{hh},\qquad \mathbf a_j=\bW_{hh}\bh_{j-1}+\bW_{xh}\bx_j+\bb_h.$$
$|\tanh'|\le1$이므로 $\Big\|\dfrac{\partial\bh_t}{\partial\bh_k}\Big\|_2\le\|\bW_{hh}\|_2^{\,t-k}$. 따라서 $\|\bW_{hh}\|_2\lt1$이면 $t-k$에 대해 지수적으로 0으로 간다. 반대로 gradient가 폭발하려면 $\|\bW_{hh}\|_2>1$이어야 한다(necessary condition).
Weight가 공유되므로 parameter의 gradient는 모든 시점의 기여를 더한 것이다. 전체 loss $\ell=\sum_t\ell_t$에 대해 $$\frac{\partial\ell}{\partial\bW_{hh}}=\sum_{t=1}^T\sum_{k=1}^{t}\frac{\partial\ell_t}{\partial\bh_t}\frac{\partial\bh_t}{\partial\bh_k}\frac{\partial^+\bh_k}{\partial\bW_{hh}},$$ 여기서 $\partial^+$는 $\bh_{k-1}$을 상수로 보고 시점 $k$에서 직접 미분한 것이다. 먼 과거($k\ll t$)의 기여는 위의 Jacobian 곱 $\partial\bh_t/\partial\bh_k$를 거치므로, 그 크기가 시간 간격에 따라 지수적으로 변한다.
같은 행렬이 반복해서 곱해지기 때문에 생기는 문제이다(weight sharing의 대가). Vanishing gradient는 먼 과거의 정보를 학습하지 못하게 하고(long-term dependency 문제), exploding gradient는 학습을 발산시킨다. Exploding 쪽은 gradient norm이 임계값 $c$를 넘으면 $\mathbf g\leftarrow c\,\mathbf g/\|\mathbf g\|$로 줄이는 gradient clipping으로 다룬다. Vanishing 쪽은 architecture를 바꿔야 한다.
7.5LSTM과 GRU
$[\bh_{t-1};\bx_t]$를 이어 붙인 vector에 대해 $$\begin{aligned} \mathbf f_t&=\sigma(\bW_f[\bh_{t-1};\bx_t]+\bb_f) &&\text{(forget gate)}\\ \mathbf i_t&=\sigma(\bW_i[\bh_{t-1};\bx_t]+\bb_i) &&\text{(input gate)}\\ \mathbf o_t&=\sigma(\bW_o[\bh_{t-1};\bx_t]+\bb_o) &&\text{(output gate)}\\ \tilde{\mathbf c}_t&=\tanh(\bW_c[\bh_{t-1};\bx_t]+\bb_c)\\ \mathbf c_t&=\mathbf f_t\odot\mathbf c_{t-1}+\mathbf i_t\odot\tilde{\mathbf c}_t\\ \bh_t&=\mathbf o_t\odot\tanh(\mathbf c_t) \end{aligned}$$
핵심은 cell state $\mathbf c_t$의 update가 곱이 아니라 덧셈이라는 점이다. Gate를 통한 간접 의존을 무시하면 $\partial\mathbf c_t/\partial\mathbf c_{t-1}=\diag(\mathbf f_t)$이므로, forget gate가 1에 가까우면 gradient가 거의 그대로 과거로 전달된다. ResNet의 skip connection과 같은 원리이다. Forget gate의 bias를 양수로 초기화하는 관행도 이 때문이다.
GRU(Cho et al., 2014)는 gate를 두 개로 줄인 변형이다. $$\mathbf z_t=\sigma(\bW_z[\bh_{t-1};\bx_t]),\quad\mathbf r_t=\sigma(\bW_r[\bh_{t-1};\bx_t]),\quad\tilde\bh_t=\tanh(\bW[\mathbf r_t\odot\bh_{t-1};\bx_t]),\quad\bh_t=(1-\mathbf z_t)\odot\bh_{t-1}+\mathbf z_t\odot\tilde\bh_t.$$ $\bh_t$가 과거 상태와 새 후보의 convex combination이라는 점이 LSTM의 cell state 역할을 한다. ($\mathbf z_t$와 $1-\mathbf z_t$의 위치는 문헌과 library마다 반대로 쓰기도 한다. PyTorch는 $\bh_t=(1-\mathbf z_t)\odot\tilde\bh_t+\mathbf z_t\odot\bh_{t-1}$이다. 의미는 같다.)
Bidirectional RNN은 정방향 RNN과 역방향 RNN을 따로 돌려 $\bh_t=[\overrightarrow{\bh}_t;\overleftarrow{\bh}_t]$로 이어 붙인다. 각 시점이 과거와 미래 문맥을 모두 보므로 tagging이나 classification에 유리하다. 단, 미래를 볼 수 없는 autoregressive generation에는 쓸 수 없다.
7.6Encoder–decoder와 그 한계
Machine translation 같은 seq2seq 문제에서는 encoder RNN이 입력 문장 전체를 마지막 hidden state $\bh_T$ 하나로 요약하고, decoder RNN이 이를 초기 상태로 받아 출력 문장을 한 token씩 생성한다. Training 때는 decoder input으로 이전 시점의 정답 token을 넣는다(teacher forcing).
문제는 입력이 아무리 길어도 고정 크기의 vector 하나로 압축해야 한다는 것이다(information bottleneck). 또 RNN은 $\bh_t$를 계산하려면 $\bh_{t-1}$이 있어야 하므로 시간 축으로 병렬화할 수 없다. Decoder가 매 시점 encoder의 모든 hidden state를 직접 참조하게 하는 attention(Bahdanau et al., 2015)이 첫 번째 문제를 풀었고, recurrence를 아예 없애고 attention만 남긴 Transformer가 두 번째 문제까지 풀었다. 다음 장의 주제이다.
Chapter 8Attention과 Transformer
Lecture Week 05 (3. Transformer)
Transformer(Vaswani et al., 2017, "Attention Is All You Need")는 recurrence를 버리고 attention과 MLP만으로 sequence를 처리한다. Attention이라는 개념 자체는 이전에도 있었지만(Bahdanau attention, CBAM 등), 이 논문의 query–key–value(QKV) attention과 그것을 쌓는 방식이 이후 NLP와 vision 모두의 표준이 되었다. 이 장에서는 attention을 행렬 연산으로 정확히 정의하고, 그 성질에서 positional encoding과 masking이 왜 필요한지 유도한다.
8.1Scaled dot-product attention
Query $\mathbf Q\in\R^{n\times d_k}$, key $\mathbf K\in\R^{m\times d_k}$, value $\mathbf V\in\R^{m\times d_v}$에 대해 $$\mathrm{Attn}(\mathbf Q,\mathbf K,\mathbf V)=\softmax\!\Big(\frac{\mathbf Q\mathbf K^\top}{\sqrt{d_k}}\Big)\mathbf V\in\R^{n\times d_v},$$ 여기서 softmax는 row별로 적용한다.
각 단계를 해석하면 다음과 같다. Query의 $i$번째 row $\mathbf q_i$와 key의 $j$번째 row $\mathbf k_j$의 내적 $\mathbf q_i^\top\mathbf k_j$는 "token $i$가 token $j$를 얼마나 참고해야 하는가"의 점수이다. 이를 row별 softmax로 확률 가중치 $A_{ij}$로 바꾸고, output의 $i$번째 row는 $$\mathbf z_i=\sum_{j=1}^m A_{ij}\mathbf v_j$$ 즉 value들의 가중평균이 된다. 강의의 예로, "I love apple"에서 첫 row는 "I"와 문장 전체("I", "love", "apple")의 점수이고, 이 점수로 문장 전체의 value를 섞은 것이 "I"의 새 표현이 된다. 각 token의 표현이 문맥 전체를 반영하도록 다시 쓰이는 것이다.
Attention output은 $$\mathbf z_i=\sum_j\frac{\kappa(\mathbf q_i,\mathbf k_j)}{\sum_{j'}\kappa(\mathbf q_i,\mathbf k_{j'})}\mathbf v_j,\qquad\kappa(\mathbf q,\mathbf k)=\exp\big(\mathbf q^\top\mathbf k/\sqrt{d_k}\big)$$ 로 쓸 수 있다. 이는 nonparametric regression의 Nadaraya–Watson estimator $\hat m(x)=\sum_j\frac{K(x,x_j)}{\sum_{j'}K(x,x_{j'})}y_j$와 같은 형태이다. Query가 "예측하려는 점", key가 "관측된 input", value가 "관측된 response"에 해당하고, kernel $\kappa$가 둘의 유사도로 가중치를 정한다. 차이는 kernel의 모양(projection $\bW_Q,\bW_K$)과 value가 모두 학습된다는 점이다.
$\mathbf q,\mathbf k\in\R^{d_k}$의 성분이 서로 independent하고 mean 0, variance 1이면 $\E[\mathbf q^\top\mathbf k]=0$, $\Var(\mathbf q^\top\mathbf k)=d_k$이다.
$\mathbf q^\top\mathbf k=\sum_{i=1}^{d_k}q_ik_i$이고 각 항은 mean 0, variance $\E[q_i^2]\E[k_i^2]=1$이며 서로 uncorrelated이다.
$d_k$가 크면 score의 크기가 $\sqrt{d_k}$ 수준으로 커지고, softmax가 거의 one-hot으로 saturate되어 gradient가 매우 작아진다. $\sqrt{d_k}$로 나누면 score의 분산이 1로 유지된다.
8.2Self-attention과 permutation equivariance
Input sequence $\mathbf X\in\R^{n\times d_{\text{model}}}$(row가 token)에서 세 개의 학습되는 projection으로 query, key, value를 만든다. $$\mathbf Q=\mathbf X\bW_Q,\quad\mathbf K=\mathbf X\bW_K,\quad\mathbf V=\mathbf X\bW_V,\qquad\bW_Q,\bW_K\in\R^{d_{\text{model}}\times d_k},\ \bW_V\in\R^{d_{\text{model}}\times d_v}.$$ Q, K, V가 모두 같은 $\mathbf X$에서 오므로 self-attention이라 한다. RNN의 recurrence 없이도 모든 token 쌍이 한 단계 만에 상호작용한다.
그런데 이 연산은 순서를 전혀 모른다. RNN은 순서대로 처리한다는 inductive bias를 가졌지만 self-attention은 단순한 행렬 곱이다.
Self-attention $\mathrm{SA}(\mathbf X)=\mathrm{Attn}(\mathbf X\bW_Q,\mathbf X\bW_K,\mathbf X\bW_V)$와 임의의 permutation matrix $\mathbf P$에 대해 $\mathrm{SA}(\mathbf P\mathbf X)=\mathbf P\,\mathrm{SA}(\mathbf X)$이다.
$\mathbf X\mapsto\mathbf P\mathbf X$이면 $\mathbf Q\mapsto\mathbf P\mathbf Q$, $\mathbf K\mapsto\mathbf P\mathbf K$, $\mathbf V\mapsto\mathbf P\mathbf V$이고 score는 $\mathbf P\mathbf Q\mathbf K^\top\mathbf P^\top/\sqrt{d_k}$가 된다. Row별 softmax는 row와 column의 재배열과 교환하므로 $\softmax(\mathbf P\mathbf S\mathbf P^\top)=\mathbf P\softmax(\mathbf S)\mathbf P^\top$. 따라서 output은 $\mathbf P\mathbf A\mathbf P^\top\mathbf P\mathbf V=\mathbf P\mathbf A\mathbf V$ ($\mathbf P^\top\mathbf P=\bI$).
Token의 순서를 섞으면 output도 같이 섞일 뿐 각 token의 표현은 변하지 않는다. "dog bites man"과 "man bites dog"을 구분할 수 없다는 뜻이다. Token-wise MLP도 같은 성질을 가지므로 Transformer 전체가 permutation equivariant이다. 그래서 위치 정보를 따로 넣어 주어야 한다.
8.3Positional encoding
Token embedding에 위치마다 다른 vector $\mathbf p_{\text{pos}}\in\R^{d_{\text{model}}}$를 더한 뒤 network에 넣는다. 원 논문의 sinusoidal positional encoding은 $$\mathbf p_{\text{pos},2i}=\sin\!\Big(\frac{\text{pos}}{10000^{2i/d_{\text{model}}}}\Big),\qquad\mathbf p_{\text{pos},2i+1}=\cos\!\Big(\frac{\text{pos}}{10000^{2i/d_{\text{model}}}}\Big)$$ 이다. 차원마다 주파수가 다른 sine/cosine을 쓰므로, 차원이 충분하면 서로 다른 위치가 겹치지 않는 고유한 code를 얻는다. 다만 이 code 자체에 "앞/뒤"의 위계가 있지는 않다.
각 주파수 $\omega_i=10000^{-2i/d_{\text{model}}}$에 대해 $(\mathbf p_{\text{pos}+k,2i},\mathbf p_{\text{pos}+k,2i+1})$는 $(\mathbf p_{\text{pos},2i},\mathbf p_{\text{pos},2i+1})$를 각도 $\omega_ik$만큼 회전한 것이다. 즉 $\mathbf p_{\text{pos}+k}=\mathbf R_k\mathbf p_{\text{pos}}$이고, $\mathbf R_k$는 pos와 무관한 block-diagonal rotation 행렬이다.
$\omega=\omega_i$, $p=\text{pos}$로 쓰면 덧셈정리에 의해 $$\begin{pmatrix}\sin\omega(p+k)\\\cos\omega(p+k)\end{pmatrix}=\begin{pmatrix}\cos\omega k&\sin\omega k\\-\sin\omega k&\cos\omega k\end{pmatrix}\begin{pmatrix}\sin\omega p\\\cos\omega p\end{pmatrix}.$$ 오른쪽 행렬은 $p$에 의존하지 않는 $2\times2$ rotation이다. 모든 $i$에 대해 모으면 block-diagonal $\mathbf R_k$를 얻는다.
상대 위치 $k$만큼의 이동이 위치와 무관한 linear map이므로, model이 상대 위치를 쉽게 학습할 수 있다는 것이 설계 의도이다. ViT와 BERT는 positional embedding 자체를 parameter로 학습한다(learned PE). 최근 LLM은 이 회전 성질을 query·key에 직접 적용하는 RoPE(rotary position embedding)를 주로 쓴다.
8.4Multi-head attention
하나의 attention은 하나의 가중치 패턴만 만든다. 문법적 관계, 지시 관계, 인접 token처럼 여러 종류의 관계를 동시에 보려면 attention을 여러 개 병렬로 둔다.
Head 수 $H$, $d_k=d_v=d_{\text{model}}/H$에 대해 $$\mathrm{head}_h=\mathrm{Attn}(\mathbf X\bW_Q^{h},\mathbf X\bW_K^{h},\mathbf X\bW_V^{h}),\qquad\mathrm{MHA}(\mathbf X)=[\mathrm{head}_1;\cdots;\mathrm{head}_H]\,\bW_O,$$ $\bW_O\in\R^{Hd_v\times d_{\text{model}}}$.
Head마다 차원을 $1/H$로 줄였으므로 전체 계산량은 single-head와 비슷하다. Parameter 수는 bias를 빼면 $4d_{\text{model}}^2$이다.
8.5Transformer block
Transformer layer는 multi-head attention과 position-wise feed-forward network(FFN)를 residual connection과 LayerNorm으로 감싼 것이다. FFN은 token마다 독립적으로 적용되는 2-layer MLP $$\mathrm{FFN}(\mathbf x)=\bW_2\,g(\bW_1\mathbf x+\bb_1)+\bb_2,\qquad\bW_1\in\R^{d_{\text{ff}}\times d_{\text{model}}},\ d_{\text{ff}}=4d_{\text{model}}$$ 이다. Attention이 token 사이의 정보를 섞고, FFN이 각 token 안에서 feature를 변환한다. 강의에서 강조했듯 Transformer의 neural network 부분은 MLP이며, 여러 technique(residual, normalization, attention)을 더해 RNN보다 좋은 성능을 낸다.
| Variant | Sub-layer 계산 | 특징 |
|---|---|---|
| Post-LN (원 논문) | $\mathbf x\leftarrow\mathrm{LN}(\mathbf x+\mathrm{Sub}(\mathbf x))$ | 깊어지면 warmup 없이는 학습이 불안정 |
| Pre-LN (현재 표준) | $\mathbf x\leftarrow\mathbf x+\mathrm{Sub}(\mathrm{LN}(\mathbf x))$ | Residual path가 identity로 깨끗하게 유지되어 안정적 |
BatchNorm 대신 LayerNorm을 쓰는 이유는 Chapter 4에서 본 것과 같다. Sequence 길이가 sample마다 다르고 padding이 섞이며 batch가 작은 경우가 많아, batch 통계를 신뢰할 수 없다. LayerNorm은 token 하나의 $d_{\text{model}}$차원 안에서 정규화하므로 이런 문제가 없다.
8.6Encoder–decoder와 masking
원래의 Transformer는 machine translation을 위한 encoder–decoder 구조이다.
- Encoder self-attention: source 문장의 token들이 서로를 본다. Q, K, V 모두 source에서 온다.
- Decoder masked self-attention: target 문장의 token들이 서로를 보되, 자기보다 뒤의 token은 보지 못한다.
- Encoder–decoder cross-attention: Query는 decoder에서, key와 value는 encoder의 최종 output $\mathbf H_{\text{enc}}$에서 온다. $\mathrm{Attn}(\mathbf Y\bW_Q,\mathbf H_{\text{enc}}\bW_K,\mathbf H_{\text{enc}}\bW_V)$이고 score 행렬은 $n_{\text{dec}}\times n_{\text{enc}}$이다. 즉 target의 각 token이 source 문장의 어디를 참고할지 정한다.
Autoregressive factorization
Decoder는 output sequence의 distribution을 $$p_\theta(y_1,\dots,y_m\mid\mathbf x)=\prod_{t=1}^m p_\theta(y_t\mid y_{\lt t},\mathbf x)$$ 로 분해해 한 token씩 예측한다(autoregressive). 예를 들어 "I love apple → 나는 사과를 좋아한다"에서 training input은 오른쪽으로 한 칸 민(shifted right) "[START] 나는 사과를 좋아한다", label은 "나는 사과를 좋아한다 [EOS]"이다. "사과를"을 예측할 때는 그 앞의 "[START] 나는"만 봐야 한다.
Causal (look-ahead) mask
Training에서는 정답 sequence 전체가 한 번에 입력되므로, 미래 token을 보지 못하게 score에 mask를 더한다. $$\mathbf A=\softmax\!\Big(\frac{\mathbf Q\mathbf K^\top}{\sqrt{d_k}}+\mathbf M\Big),\qquad M_{ij}=\begin{cases}0 & j\le i\\-\infty & j>i\end{cases}$$ $e^{-\infty}=0$이므로 softmax 후 upper triangle은 정확히 0이 된다(구현에서는 매우 큰 음수를 더한다). Batch 안의 문장 길이를 맞추려고 붙인 padding token을 key에서 제외하는 padding mask도 같은 방식으로 구현한다. 덕분에 모든 위치의 다음 token 예측을 한 번의 forward pass로 병렬 학습할 수 있다(teacher forcing). Inference에서는 실제로 예측한 token을 하나씩 다시 넣으며 [EOS]가 나올 때까지 반복한다. 이때는 애초에 미래 token이 없으므로 mask가 있든 없든 같은 계산이 되며, training의 mask는 test 상황을 정확히 흉내 내기 위한 장치이다.
이후의 model들은 이 구조의 일부만 쓴다. BERT는 encoder만, GPT는 masked self-attention decoder만(Chapter 26), ViT는 encoder만(Chapter 9) 쓴다.
8.7Complexity
Self-attention의 score 행렬 $\mathbf Q\mathbf K^\top$ 계산은 $O(n^2d_k)$, 그 결과와 $\mathbf V$의 곱은 $O(n^2d_v)$이므로 layer당 $O(n^2d)$ 시간과 $O(n^2)$ memory가 든다. Sequence 길이에 대해 quadratic이다.
| Layer | Time per layer | Sequential ops | Max path length |
|---|---|---|---|
| Self-attention | $O(n^2d)$ | $O(1)$ | $O(1)$ |
| Recurrent | $O(nd^2)$ | $O(n)$ | $O(n)$ |
| Convolution (kernel $k$) | $O(knd^2)$ | $O(1)$ | $O(\log_kn)$ |
Self-attention은 모든 token 쌍이 한 단계로 연결되고(긴 의존성 학습에 유리) 완전히 병렬화된다. 대가는 긴 sequence에서의 quadratic cost이며, 다음 장의 Perceiver는 이 문제를 정면으로 다룬다.
Chapter 9Vision Transformer와 Perceiver
Lecture Week 05 (4. Vision Transformer, 5. Perceiver)
Transformer는 sequence를 받는다. Image를 sequence로 바꾸기만 하면 같은 architecture를 vision에 쓸 수 있다는 것이 Vision Transformer(ViT)의 아이디어이다. 이 장에서는 ViT의 구성과 CNN 대비 inductive bias의 차이, 그리고 attention의 quadratic cost 문제를 latent array로 우회하는 Perceiver를 다룬다.
9.1Image를 patch sequence로
Image $\mathbf x\in\R^{H\times W\times C}$를 $P\times P$ 크기의 겹치지 않는 patch로 자르면 patch 수는 $N=HW/P^2$이다. 각 patch를 flatten하면 $\mathbf x_p^i\in\R^{P^2C}$이므로 image 전체는 $$\mathbf x_p\in\R^{N\times(P^2C)}$$ 인 sequence가 된다. Patch 하나가 문장의 단어 하나, patch의 개수가 문장의 길이, patch vector의 길이가 embedding 차원에 대응한다. 예를 들어 $12\times12\times3$ image에 $P=4$이면 $N=9$개의 48차원 vector이고, 표준 설정인 $224\times224\times3$, $P=16$이면 $N=196$개의 768차원 vector이다. $P$는 patch의 크기이지 개수가 아님에 주의한다.
9.2ViT의 구성
Patch embedding $\mathbf E\in\R^{(P^2C)\times D}$, class token $\mathbf x_{\text{class}}\in\R^{1\times D}$, position embedding $\mathbf E_{\text{pos}}\in\R^{(N+1)\times D}$에 대해 $$\begin{aligned} \mathbf z_0&=[\mathbf x_{\text{class}};\,\mathbf x_p^1\mathbf E;\,\mathbf x_p^2\mathbf E;\,\cdots;\,\mathbf x_p^N\mathbf E]+\mathbf E_{\text{pos}}\in\R^{(N+1)\times D},\\ \mathbf z'_\ell&=\mathrm{MHA}(\mathrm{LN}(\mathbf z_{\ell-1}))+\mathbf z_{\ell-1},\qquad\ell=1,\dots,L,\\ \mathbf z_\ell&=\mathrm{FFN}(\mathrm{LN}(\mathbf z'_\ell))+\mathbf z'_\ell,\\ \mathbf y&=\mathrm{LN}(\mathbf z_L^0)\in\R^{1\times D}. \end{aligned}$$ $\mathbf z_L^0$는 $\mathbf z_L$의 첫 row(class token 위치)이며, classification은 $\mathbf y$ 위에 MLP head를 둔다.
Transformer encoder(Pre-LN)만 있고 decoder는 없다. Patch embedding $\mathbf E$는 모든 layer의 차원을 $D$로 맞춰 encoder에 들어갈 준비를 하는 단계이며, kernel size와 stride가 모두 $P$인 convolution과 같은 연산이다. Class token은 처음에는 image와 무관한 학습 parameter이지만, 매 layer의 self-attention을 통해 모든 patch의 정보를 모으므로 마지막 layer에서는 image 전체의 요약이 된다. Class token 대신 patch output들의 평균(GAP)을 써도 성능은 비슷하다.
$D=768$, $L=12$, head 12개, $d_{\text{ff}}=3072$, $224\times224$ input($N=196$), 1000-class head일 때(bias와 LayerNorm 포함):
Patch embedding $768\cdot768+768=590{,}592$; class token $768$; position embedding $197\cdot768=151{,}296$.
Layer 하나: MHA $4(768^2+768)=2{,}362{,}368$, FFN $2\cdot768\cdot3072+3072+768=4{,}722{,}432$, LayerNorm 두 개 $3{,}072$, 합 $7{,}087{,}872$. 12개이면 $85{,}054{,}464$.
마지막 LayerNorm $1{,}536$, classification head $768\cdot1000+1000=769{,}000$.
총 $86{,}567{,}656$개, 약 86M이다. 대부분이 Transformer layer에 있고, 특히 FFN이 attention의 두 배이다.
Chapter 8의 해석을 그대로 적용하면, 각 layer output의 $i$번째 row는 "$i$번째 patch와 image 전체 patch 사이의 attention score로 가중합한 표현"이다. CNN과 달리 첫 layer부터 image 반대편의 patch를 직접 참조할 수 있다.
9.3Inductive bias와 data 규모
CNN은 locality와 translation equivariance(Proposition 6.3)를 구조로 강제한다. ViT에는 그런 가정이 거의 없다. Image에 대한 가정은 patch를 grid로 자른다는 것과 position embedding뿐이며, 어느 patch가 이웃인지조차 학습해야 한다. 주요 구조의 inductive bias를 비교하면 다음과 같다.
| Component | Entities | Relations | Relational inductive bias | Invariance |
|---|---|---|---|---|
| Fully connected | Units | All-to-all | Weak | 없음 |
| Convolutional | Grid elements | Local | Locality | Spatial translation |
| Recurrent | Timesteps | Sequential | Sequentiality | Time translation |
| Graph network | Nodes | Edges | Arbitrary | Node, edge permutation |
| Self-attention | Tokens | All-to-all (data-dependent weight) | Weak | Permutation (PE 없을 때) |
앞 네 줄은 Battaglia et al.(2018)의 정리이고(graph network는 Chapter 11에서 다룬다), 마지막 줄은 Chapter 8의 결과를 덧붙인 것이다. Self-attention은 모든 token 쌍을 연결한다는 점에서 fully connected와 비슷하지만, 연결의 weight가 고정 parameter가 아니라 input에 따라 계산된다. (엄밀히는 CNN과 RNN의 "invariance" 열은 equivariance를 뜻한다.)
Inductive bias는 사람이 아는 prior를 model에 넣은 것이다. Prior가 적으면 그만큼 data로 배워야 하므로 더 많은 data와 계산이 필요하다. 실제로 ImageNet-1k(약 130만 장)만으로 학습하면 ViT는 같은 크기의 ResNet보다 성능이 낮다. 반면 ImageNet-21k(약 1,400만 장)나 JFT-300M으로 pre-training하면 ResNet을 넘어서고, model과 data를 키울수록 성능이 계속 오른다(scalability). 통계적으로 말하면 bias–variance trade-off이다. 가정이 강한 model은 작은 sample에서 variance가 작고, 가정이 약한 model은 큰 sample에서 bias가 작다. 이후 DeiT(Touvron et al., 2021)는 강한 data augmentation과 knowledge distillation(Chapter 12)으로 ImageNet-1k만으로도 ViT를 잘 학습할 수 있음을 보였다.
9.4해상도가 달라지면
ViT의 parameter($\mathbf E$, attention과 FFN의 weight)는 모두 token 하나의 차원 $D$에만 의존하고 token의 개수 $N$과는 무관하다. 행렬 곱 $\mathbf C=\mathbf A\mathbf B$에서 $\mathbf C$의 $n$번째 row는 $\mathbf A$의 $n$번째 row와 $\mathbf B$ 전체로 결정된다. Row의 개수와 순서는 $\mathbf B$와 상관이 없다. 그래서 patch 크기 $P$만 유지하면 image 크기가 달라져 $N$이 바뀌어도 같은 weight를 쓸 수 있다.
유일하게 길이가 고정된 것은 $\mathbf E_{\text{pos}}\in\R^{(N+1)\times D}$이다. 해상도를 바꿀 때는 patch position embedding을 원래의 2D grid 모양으로 되돌린 뒤 2D interpolation으로 새 grid 크기에 맞춘다. 고해상도 fine-tuning에서 표준적으로 쓰는 방법이다.
9.5Complexity와 patch 크기
Attention cost는 $O(N^2D)$이고 $N=HW/P^2$이므로 $$O\Big(\frac{H^2W^2}{P^4}D\Big).$$ Patch 크기를 절반으로 줄이면 token 수가 4배, attention cost가 16배가 된다. 그래서 ViT는 pixel 단위가 아니라 큰 patch 단위로 작동해야 하고, 이것이 결국 "image는 grid 구조"라는 vision 전용 inductive bias를 다시 들여오는 셈이 된다. 결과적으로 ViT는 image만 다루는 modality-specific model이다.
9.6Perceiver: latent bottleneck으로 quadratic cost 피하기
사람은 시각, 청각, 촉각을 동시에 처리한다. Perceiver(Jaegle et al., 2021)는 modality에 대한 가정 없이 임의의 input을 같은 architecture로 처리하는 것을 목표로 한다. 걸림돌은 quadratic scaling이다. $224\times224$ image를 pixel 단위 token으로 보면 $M=50{,}176$이고, self-attention의 $M\times M$ 행렬은 감당할 수 없다.
QKV attention 구조를 유지하면서 cost를 줄이려면 score 행렬 $\mathbf Q\mathbf K^\top$의 크기를 줄여야 하고, 그러려면 query의 개수를 줄여야 한다. Perceiver는 query를 input에서 만들지 않고 따로 둔 작은 latent array에서 만든다.
Byte array $\mathbf X\in\R^{M\times C}$ (input, $M$이 큼)와 학습되는 latent array $\mathbf Z\in\R^{N\times D}$ ($N\ll M$)에 대해
(1) Cross-attention: $\mathbf Q=\mathbf Z\bW_Q\in\R^{N\times D}$, $\mathbf K=\mathbf X\bW_K,\ \mathbf V=\mathbf X\bW_V\in\R^{M\times D}$ ($\bW_K,\bW_V\in\R^{C\times D}$)로 $\mathbf Z\leftarrow\mathrm{Attn}(\mathbf Q,\mathbf K,\mathbf V)\in\R^{N\times D}$.
(2) Latent transformer: $\mathbf Z$에 일반 Transformer layer(self-attention + FFN)를 $L$번 적용한다.
(1)–(2)를 반복할 수 있으며, 반복되는 block끼리 weight를 공유할 수 있다.
Cross-attention의 score 행렬은 $N\times M$이므로 cost는 $O(NMD)$로 input 크기에 linear하다. Latent transformer의 self-attention은 $O(N^2D)$로 input 크기와 무관하다. 전체 cost는 $$O(MND)+O(LN^2D)\quad\text{vs.}\quad O(LM^2D)\ \text{(input에 직접 Transformer)}.$$ ImageNet 예에서 $M=50{,}176$을 $N=512$로 줄이는 것이다. $D=1024$, latent layer $L=6$으로 score 계산의 곱셈 수를 대략 비교하면, Perceiver는 $MND+LN^2D\approx2.6\times10^{10}+1.6\times10^{9}$, input에 직접 6층 Transformer를 쓰면 $LM^2D\approx1.5\times10^{13}$으로 약 550배 차이가 난다. Cross-attention은 상대적으로 비싸므로 한 번(또는 몇 번)만 쓰고, representation 학습은 대부분 latent 공간에서 반복되는 Transformer가 담당한다. Cross-attention은 representation을 배운다기보다 byte와 latent를 연결하는 역할로 보는 편이 맞다.
Perceiver는 위치 정보를 Fourier feature positional encoding으로 byte array에 붙이므로, image든 audio든 point cloud든 같은 구조로 처리한다. Inductive bias와 계산량 사이의 trade-off에서 bias를 최소화하고 계산 문제는 latent bottleneck으로 해결한 설계라 할 수 있다. 같은 아이디어(소수의 learned query가 큰 input을 cross-attend)는 이후 DETR, BLIP-2의 Q-Former 등 multimodal model에서 반복해서 쓰인다.
Chapter 10긴 Sequence: 효율적인 Attention과 State Space Model
새로 추가한 장 (강의 범위 밖). Su et al. 2021; Dao et al. 2022; Katharopoulos et al. 2020; Gu et al. 2022; Gu & Dao 2023
Self-attention은 길이 $n$의 sequence에 $O(n^2)$의 계산과 memory를 쓴다(Chapter 8). 수만 token의 문서, 수십만 sample의 생체신호나 audio에서는 이것이 병목이다. 이 장은 두 방향을 다룬다. 첫째, attention을 유지하면서 실제 비용을 줄이는 기법: 생성 시 KV cache와 그것을 줄이는 grouped-query attention, 상대 위치를 회전으로 넣는 RoPE, 그리고 memory 접근을 줄여 정확한 attention을 빠르게 계산하는 FlashAttention이다. 둘째, attention을 대신하는 선형 시간 sequence model: linear attention과 state space model(S4, Mamba)이다. 후자는 RNN(Chapter 7)과 convolution(Chapter 6)이 같은 model의 두 얼굴이라는 사실 위에 서 있다.
10.1생성의 비용과 KV cache
Autoregressive 생성(Chapter 26)에서 token $t$를 만들려면 query $\bq_t$와 지금까지의 모든 key·value $\bk_{1:t},\bv_{1:t}$의 attention이 필요하다. 이전 token의 key·value는 바뀌지 않으므로 매번 다시 계산하지 않고 저장해 두는 것이 KV cache이다. 그러면 token 하나를 생성하는 데 $O(td)$만 들지만, cache의 memory가 sequence 길이에 비례해 늘어난다. Layer 수 $L$, model 차원 $d$, 16-bit 저장이면 token당 $2\cdot L\cdot d\cdot2$ byte이다. $L=32$, $d=4096$인 7B 규모 model에서 token당 0.5MB, 4,096 token이면 sequence 하나에 2GB로, batch를 키우면 weight보다 cache가 더 큰 memory를 차지한다.
Cache를 줄이는 가장 효과적인 방법은 여러 head가 key·value를 공유하는 것이다. 모든 head가 하나의 key·value head를 쓰는 multi-query attention(MQA; Shazeer, 2019)과, head를 $G$개 group으로 나눠 group마다 하나씩 쓰는 grouped-query attention(GQA; Ainslie et al., 2023)이 있다. 32개 query head에 8개 key·value head를 쓰면 cache가 1/4(token당 0.125MB)이 되며, 성능 손실은 작다. 최근 대부분의 공개 LLM이 GQA를 쓴다.
10.2Rotary position embedding
Chapter 8의 sinusoidal positional encoding은 위치 vector를 input에 더한다. 그런데 attention score에 필요한 것은 절대 위치가 아니라 두 token 사이의 거리이다. Query와 key에 위치에 따라 회전을 걸면 score가 상대 위치에만 의존하게 만들 수 있다(RoPE; Su et al., 2021).
$d$차원 vector를 2차원씩 $d/2$개 쌍으로 묶고, 쌍 $i$에 각도 $m\theta_i$의 회전 $\mathbf R(m\theta_i)=\begin{pmatrix}\cos m\theta_i&-\sin m\theta_i\\\sin m\theta_i&\cos m\theta_i\end{pmatrix}$을 거는 block-diagonal 행렬을 $\mathbf R_m$이라 하자($\theta_i=10000^{-2i/d}$). 그러면 $$(\mathbf R_m\bq)^\top(\mathbf R_n\bk)=\bq^\top\mathbf R_{n-m}\bk.$$
각 block에서 $\mathbf R(\alpha)^\top=\mathbf R(-\alpha)$이고 $\mathbf R(\alpha)\mathbf R(\beta)=\mathbf R(\alpha+\beta)$이므로 $\mathbf R_m^\top\mathbf R_n=\mathbf R_{n-m}$이다.
위치 $m$의 query와 위치 $n$의 key의 score는 $n-m$과 내용 $\bq,\bk$로만 정해진다. 복소수로 쓰면 쌍 $(q_{2i},q_{2i+1})$를 $q_{2i}+\mathrm iq_{2i+1}$로 보고 $e^{\mathrm im\theta_i}$를 곱하는 것이다. 주파수 $\theta_i$가 고주파에서 저주파까지 기하급수로 퍼져 있어(sinusoidal encoding과 같은 설계), 가까운 token은 고주파 성분으로, 먼 token은 저주파 성분으로 구분된다. 학습 길이보다 긴 문맥에 쓰려면 위치를 줄여 넣는 position interpolation(Chen et al., 2023)이나 주파수별로 다르게 늘리는 YaRN(Peng et al., 2023) 같은 방법으로 회전 각도를 조정한 뒤 짧게 추가 학습한다.
10.3FlashAttention: 같은 계산, 다른 memory 접근
GPU에서 attention이 느린 주된 이유는 곱셈의 수가 아니라 memory 이동이다. 표준 구현은 $n\times n$ score 행렬 $\mathbf S$와 softmax 결과 $\mathbf A$를 큰 GPU memory(HBM)에 썼다가 다시 읽는다. 연산 장치 옆의 작은 고속 memory(SRAM)는 수십 배 빠르지만 $n\times n$ 행렬을 담을 수 없다. FlashAttention(Dao et al., 2022)은 $\bQ,\bK,\bV$를 block으로 나눠 SRAM에서 계산하고 $\mathbf S$를 HBM에 한 번도 쓰지 않는다. 문제는 softmax가 row 전체의 합을 알아야 정규화된다는 것인데, 다음 사실로 해결된다.
Score $\mathbf s=(\mathbf s^{(1)},\mathbf s^{(2)})$와 value $\bV=(\bV^{(1)};\bV^{(2)})$를 두 block으로 나누고, 각 block에서 $m_j=\max\mathbf s^{(j)}$, $\ell_j=\sum e^{\mathbf s^{(j)}-m_j}$, $\mathbf o_j=\frac1{\ell_j}\sum e^{\mathbf s^{(j)}-m_j}\bV^{(j)}$를 계산했다면, $m=\max(m_1,m_2)$에 대해 $$\ell=e^{m_1-m}\ell_1+e^{m_2-m}\ell_2,\qquad\softmax(\mathbf s)^\top\bV=\frac{e^{m_1-m}\ell_1\,\mathbf o_1+e^{m_2-m}\ell_2\,\mathbf o_2}{\ell}.$$
$\sum_ie^{s_i-m}=\sum_{i\in1}e^{s_i-m_1}e^{m_1-m}+\sum_{i\in2}e^{s_i-m_2}e^{m_2-m}=\ell$이고, 분자의 $\sum_ie^{s_i-m}\bv_i$도 같은 방식으로 $e^{m_1-m}\ell_1\mathbf o_1+e^{m_2-m}\ell_2\mathbf o_2$이다. Max를 빼는 것은 overflow를 막기 위함이며 결과를 바꾸지 않는다.
즉 key·value block을 하나씩 읽으면서 (max, 정규화 상수, 부분 output) 세 값만 갱신하면 정확한 attention output을 얻는다(Milakov & Gimelshein, 2018). 근사가 아니므로 결과는 표준 attention과 수치 오차 범위에서 같고, memory는 $O(n^2)$에서 $O(n)$으로 줄어든다. Backward에서는 $\mathbf A$를 저장하지 않고 block별로 다시 계산한다. 계산은 약간 늘지만 memory 이동이 줄어 전체는 몇 배 빠르다. 같은 연산을 hardware의 memory 계층에 맞게 재배열하는 것만으로 긴 문맥 학습이 가능해졌다는 점에서, 알고리즘의 점근적 복잡도와 실제 속도가 다를 수 있음을 보여 준다.
10.4Linear attention: attention을 RNN으로
점근적 비용 자체를 줄이려면 attention의 형태를 바꿔야 한다. 고정된 window 안의 token만 보는 sliding-window attention(일부 global token과 함께; Longformer, Beltagy et al., 2020)은 $O(nw)$이다. 다른 방법은 softmax kernel $\exp(\bq^\top\bk)$를 feature map의 내적 $\phi(\bq)^\top\phi(\bk)$로 바꾸는 것이다(Katharopoulos et al., 2020). Causal attention의 output은 $$\mathbf o_t=\frac{\sum_{i\le t}\phi(\bq_t)^\top\phi(\bk_i)\,\bv_i}{\sum_{i\le t}\phi(\bq_t)^\top\phi(\bk_i)}=\frac{\phi(\bq_t)^\top\mathbf S_t}{\phi(\bq_t)^\top\mathbf z_t},\qquad\mathbf S_t=\mathbf S_{t-1}+\phi(\bk_t)\bv_t^\top,\quad\mathbf z_t=\mathbf z_{t-1}+\phi(\bk_t)$$ 이 된다. 결합 순서를 바꿔 $\phi(\bK)^\top\bV$를 먼저 계산하므로 $O(n)$이고, 생성 시에는 고정 크기 state $(\mathbf S_t,\mathbf z_t)$만 갱신하는 RNN이다. KV cache가 필요 없다. 대가는 표현력이다. 모든 과거가 $d\times d$ 크기의 state 하나에 더해지기만 하므로 오래된 정보를 지우거나 특정 token을 정확히 찾아 꺼내는(recall) 능력이 softmax attention보다 약하다. 이 "고정 크기 state에 무엇을 남기고 무엇을 잊을 것인가"가 다음 절 state space model의 핵심 질문이다.
10.5State space model
제어이론과 시계열 분석의 linear state space model은 연속 시간에서 $$\mathbf h'(t)=\bA\mathbf h(t)+\bB u(t),\qquad y(t)=\mathbf C\mathbf h(t)$$ 로 쓰인다. Input $u$와 output $y$는 scalar(각 channel마다 독립적으로 적용), state $\mathbf h\in\R^N$이다. Noise를 넣고 $\mathbf h$를 latent로 추정하면 Kalman filter의 model이 된다. Sequence model로 쓰려면 step 크기 $\Delta$로 discretize한다. $u$가 step 안에서 일정하다고 보는 zero-order hold를 쓰면 $$\mathbf h_k=\bar\bA\mathbf h_{k-1}+\bar\bB u_k,\qquad y_k=\mathbf C\mathbf h_k,\qquad\bar\bA=e^{\Delta\bA},\quad\bar\bB=(\Delta\bA)^{-1}\big(e^{\Delta\bA}-\bI\big)\Delta\bB$$ 이다. 이것은 linear RNN이다.
$\mathbf h_0=\mathbf 0$에서 위 recurrence의 output은 kernel $\bar{\mathbf K}=(\mathbf C\bar\bB,\ \mathbf C\bar\bA\bar\bB,\ \mathbf C\bar\bA^2\bar\bB,\dots)$와의 causal convolution이다: $$y_k=\sum_{j=0}^{k-1}\mathbf C\bar\bA^j\bar\bB\,u_{k-j}.$$
Recurrence를 풀면 $\mathbf h_k=\sum_{j=0}^{k-1}\bar\bA^j\bar\bB u_{k-j}$이다($k$에 대한 귀납법). 양변에 $\mathbf C$를 곱한다.
같은 layer를 두 방식으로 계산할 수 있다는 것이 SSM의 장점이다. 학습 때는 전체 sequence가 주어지므로 kernel $\bar{\mathbf K}$를 만들고 FFT로 convolution을 $O(L\log L)$에 병렬 계산한다(CNN처럼). 생성 때는 state $\mathbf h_k$ 하나만 들고 step마다 $O(N)$으로 갱신한다(RNN처럼, KV cache 없음). Transformer는 학습은 병렬이지만 생성 비용이 문맥 길이에 비례하고, RNN은 생성은 싸지만 학습이 순차적이었다. SSM은 둘의 장점을 모두 갖는다.
남는 문제는 $\bar\bA^j$의 거듭제곱이 폭발하거나 소멸하는 것(Chapter 7의 vanishing gradient와 같은 문제)과 kernel 계산 비용이다. S4(Gu et al., 2022)는 과거 input을 Legendre 다항식 기저로 최적 근사하도록 유도된 HiPPO 행렬로 $\bA$를 초기화하고, 대각 성분과 low-rank 보정으로 이루어진 구조를 이용해 kernel을 효율적으로 계산했다. 길이 16,000의 sequence에서 먼 위치 사이의 관계를 판단해야 하는 Long Range Arena의 Path-X task에서 chance 수준을 처음으로 넘은 model이다. 이후 $\bA$를 그냥 대각(복소수) 행렬로 두어도 거의 같은 성능이 난다는 것이 알려졌다(S4D). 대각 $\bA=\diag(\lambda_n)$이면 $\bar\bA^j=\diag(e^{j\Delta\lambda_n})$이므로 kernel은 $\mathrm{Re}\,\lambda_n\lt0$인 지수 감쇠(와 진동) 함수들의 선형 결합이다. 각 state 차원이 서로 다른 시간 척도의 기억을 담당한다.
10.6Selective SSM: Mamba
S4의 parameter $\bar\bA,\bar\bB,\mathbf C$는 시간에 따라 변하지 않는다(linear time-invariant, LTI). 그래서 convolution으로 쓸 수 있지만, input 내용에 따라 "이 token은 기억하고 저 token은 무시한다"를 결정할 수 없다. 언어처럼 중요한 정보가 드문드문 나타나는 data에서 이것이 Transformer에 뒤지는 이유였다. Mamba(Gu & Dao, 2023)는 $\Delta,\bB,\mathbf C$를 input의 함수로 만든다. $$\Delta_k=\mathrm{softplus}(\mathbf w_\Delta^\top\bx_k+b_\Delta),\quad\bB_k=\bW_B\bx_k,\quad\mathbf C_k=\bW_C\bx_k,\qquad\mathbf h_k=e^{\Delta_k\bA}\mathbf h_{k-1}+\Delta_k\bB_ku_k,\quad y_k=\mathbf C_k\mathbf h_k.$$ ($\bar\bB$는 1차 근사 $\Delta\bB$로 단순화한다.) $\Delta_k$가 크면 $e^{\Delta_k\bA}\approx\mathbf 0$이 되어 이전 state를 지우고 현재 input을 강하게 쓰고, $\Delta_k$가 작으면 state를 그대로 유지하고 현재 input을 무시한다. LSTM의 forget gate와 input gate(Chapter 7)를 하나의 연속 parameter로 묶은 것이며, 1차원에서는 $h_k=e^{-\Delta_k}h_{k-1}+(1-e^{-\Delta_k})u_k$ 같은 input 의존 지수평활이다.
Parameter가 시간에 따라 변하므로 더 이상 convolution으로 계산할 수 없다. 대신 recurrence $h_k=a_kh_{k-1}+b_k$는 결합 법칙을 만족하는 연산 $(a_1,b_1)\circ(a_2,b_2)=(a_2a_1,\ a_2b_1+b_2)$의 누적이므로, prefix sum과 같은 parallel scan으로 $O(\log L)$ 깊이에 병렬 계산할 수 있다. Mamba는 이를 FlashAttention처럼 SRAM 안에서 수행하는 kernel로 구현해, 길이에 선형인 비용으로 같은 크기의 Transformer와 비슷한 언어 modeling 성능을 냈다. 후속 연구인 Mamba-2(Dao & Gu, 2024)는 선택적 SSM이 특수한 구조의 mask를 가진 (linear) attention과 수학적으로 동등함을 보였고, 두 계열을 같은 틀에서 이해하게 했다.
10.7무엇을 언제 쓰는가
| 방법 | 학습 비용 | 생성 비용(token당) | 정확한 attention? | 강점과 약점 |
|---|---|---|---|---|
| Softmax attention + FlashAttention | $O(n^2)$, memory $O(n)$ | $O(n)$ + KV cache | 예 | Recall이 가장 강함. 긴 문맥에서 비용 큼 |
| GQA/MQA | 같음 | Cache 1/G | 예(구조만 다름) | 추론 memory 절감의 표준 |
| Sliding window | $O(nw)$ | $O(w)$ | Window 안에서만 | 먼 의존성은 층을 쌓아 간접 전달 |
| Linear attention | $O(n)$ | $O(1)$ | 아니오 | State가 고정 크기, 정확한 recall 약함 |
| LTI SSM (S4) | $O(n\log n)$ (FFT) | $O(1)$ | 아니오 | 연속 신호(audio, 생체신호)의 장거리 의존성에 강함 |
| Selective SSM (Mamba) | $O(n)$ (scan) | $O(1)$ | 아니오 | Content-based 선택, 긴 sequence에서 효율적 |
현재는 attention layer 일부와 SSM layer를 섞은 hybrid architecture(예: Jamba; Lieber et al., 2024)도 많이 쓰인다. SSM layer가 대부분의 문맥을 싸게 요약하고, 소수의 attention layer가 정확한 검색을 담당한다. 생체신호처럼 sampling rate가 높아 sequence가 매우 긴 data에서는 patch로 묶어 Transformer에 넣는 방식(Chapter 9의 ViT와 같은 발상)과 SSM이 주로 비교된다.
Chapter 11Graph Neural Network
새로 추가한 장 (강의 범위 밖). Kipf & Welling 2017; Hamilton et al. 2017; Veličković et al. 2018; Xu et al. 2019
지금까지의 data는 grid(image), sequence(text), 또는 순서 없는 집합(token)이었다. 분자는 원자와 결합으로, 논문은 인용 관계로, 사회 관계망은 사람과 관계로 이루어진 graph이다. Graph에는 정해진 순서도, 고정된 이웃 수도 없다. 이 장에서는 graph 위의 함수가 가져야 할 대칭성(permutation invariance와 equivariance)에서 출발해, message passing이라는 공통 틀과 GCN, GraphSAGE, GAT를 유도하고, Weisfeiler–Lehman test로 본 표현력의 한계와 깊게 쌓을 때 생기는 over-smoothing을 다룬다. Chapter 9의 inductive bias 표에서 "Graph network" 행에 해당하는 내용이다.
11.1Graph와 task
Graph $G=(V,E)$는 node 집합 $V$($|V|=n$)와 edge 집합 $E\subseteq V\times V$로 이루어진다. 이 장에서는 주로 undirected graph를 다룬다. Graph를 행렬로 쓰면 adjacency matrix $\bA\in\{0,1\}^{n\times n}$($A_{uv}=1\iff(u,v)\in E$), node feature matrix $\bX\in\R^{n\times d}$(row $\bx_v$가 node $v$의 feature), degree matrix $\mathbf D=\diag(d_1,\dots,d_n)$, $d_v=\sum_uA_{vu}$이다. Node $v$의 이웃을 $\mathcal N(v)=\{u:A_{vu}=1\}$로 쓴다. Edge에도 feature $\mathbf e_{uv}$(결합의 종류, 거리 등)가 있을 수 있다.
Task는 예측 대상에 따라 세 가지로 나뉜다.
| 수준 | 예측 대상 | 예 |
|---|---|---|
| Node-level | 각 node의 label | 논문 인용 network에서 논문 분야 분류(Cora), 사용자 속성 예측 |
| Edge-level | 두 node 사이의 edge 유무나 종류 | 추천(사용자–상품 link prediction), 약물 상호작용 |
| Graph-level | graph 전체의 label | 분자의 물성·독성 예측, 단백질 분류 |
Node-level task는 흔히 하나의 큰 graph에서 일부 node만 label이 있는 semi-supervised 설정이다. Training 중에도 label 없는 node의 feature와 연결 구조는 쓸 수 있으므로(transductive), 이웃을 통해 label 정보가 퍼지는 것이 학습의 핵심이 된다.
11.2Permutation symmetry
Graph의 node에 붙인 번호는 임의적이다. 같은 graph를 다른 순서로 번호를 매기면 permutation matrix $\bP$에 대해 $(\bX,\bA)$가 $(\bP\bX,\bP\bA\bP^\top)$로 바뀐다. 이 둘은 같은 graph이므로 model의 답도 일관되어야 한다.
모든 permutation matrix $\bP$에 대해
graph-level function $f$가 permutation invariant: $f(\bP\bX,\bP\bA\bP^\top)=f(\bX,\bA)$,
node-level function $F:\R^{n\times d}\times\R^{n\times n}\to\R^{n\times d'}$가 permutation equivariant: $F(\bP\bX,\bP\bA\bP^\top)=\bP F(\bX,\bA)$.
$\bA$를 펼쳐 MLP에 넣는 방식은 이 조건을 만족하지 않고, $n$이 바뀌면 쓸 수도 없다. Chapter 6의 CNN이 translation equivariance를 구조로 강제했듯이, graph network는 permutation equivariance를 구조로 강제한다. Chapter 8에서 positional encoding 없는 self-attention이 permutation equivariant임(Theorem 8.4)을 보았는데, 이는 모든 token이 서로 연결된 complete graph의 특수한 경우이다.
11.3Message passing
대부분의 GNN은 다음 틀로 쓸 수 있다(Gilmer et al., 2017).
$\bh_v^{(0)}=\bx_v$에서 시작해 $l=0,\dots,L-1$에 대해 $$\mathbf m_v^{(l)}=\bigoplus_{u\in\mathcal N(v)}\psi^{(l)}\big(\bh_v^{(l)},\bh_u^{(l)},\mathbf e_{uv}\big),\qquad\bh_v^{(l+1)}=\varphi^{(l)}\big(\bh_v^{(l)},\mathbf m_v^{(l)}\big).$$ $\psi$는 message function, $\varphi$는 update function(둘 다 MLP 등 학습되는 함수이고 모든 node가 공유한다), $\bigoplus$는 sum, mean, max처럼 입력의 순서와 무관한 aggregation이다. Graph-level output은 readout $\bh_G=\rho\big(\bigoplus_{v\in V}\bh_v^{(L)}\big)$로 얻는다.
Definition 11.2의 각 layer는 permutation equivariant이고, readout까지 포함한 graph-level output은 permutation invariant이다.
Permutation $\pi$로 node 번호를 바꾸면 새 graph에서 node $\pi(v)$의 feature와 이웃 집합은 원래 graph에서 node $v$의 것과 같다($\mathcal N'(\pi(v))=\pi(\mathcal N(v))$). $\bigoplus$는 multiset에만 의존하므로 $\mathbf m'_{\pi(v)}=\mathbf m_v$이고, $\varphi$가 모든 node에 같은 함수이므로 $\bh'_{\pi(v)}=\bh_v$이다. 이것이 행렬로 $\bH'=\bP\bH$이다. Layer를 합성해도 equivariance가 유지되고, 마지막의 $\bigoplus_v$는 순서와 무관하므로 readout은 invariant이다.
$L$개 layer를 쌓은 GNN에서 $\bh_v^{(L)}$는 $v$에서 거리 $L$ 이내의 node에만 의존한다. CNN의 receptive field와 같은 개념이다. CNN은 grid graph 위의 message passing으로 볼 수 있는데, 차이는 이웃의 상대 위치(위, 아래, 왼쪽, …)마다 다른 kernel weight를 쓴다는 것이다. 일반 graph에는 이웃 사이의 정해진 순서나 방향이 없으므로 이웃을 대칭적으로 다룰 수밖에 없다.
11.4Graph convolutional network
가장 널리 쓰이는 GNN인 GCN(Kipf & Welling, 2017)의 layer는 $$\bH^{(l+1)}=\sigma\big(\hat\bA\bH^{(l)}\bW^{(l)}\big),\qquad\hat\bA=\tilde{\mathbf D}^{-1/2}\tilde\bA\tilde{\mathbf D}^{-1/2},\quad\tilde\bA=\bA+\bI,\quad\tilde d_v=\sum_u\tilde A_{vu}$$ 이다. Node 단위로 쓰면 $\bh_v^{(l+1)}=\sigma\big(\sum_{u\in\mathcal N(v)\cup\{v\}}\frac{1}{\sqrt{\tilde d_u\tilde d_v}}\bW^{(l)\top}\bh_u^{(l)}\big)$로, 자기 자신을 포함한 이웃의 feature를 degree로 정규화해 평균 내고 공유 weight로 변환하는 message passing이다. 이 형태는 graph 위의 신호처리에서 유도된다.
$\mathbf L=\mathbf D-\bA$를 (combinatorial) graph Laplacian, $\mathbf L_{\text{sym}}=\bI-\mathbf D^{-1/2}\bA\mathbf D^{-1/2}$를 normalized Laplacian이라 한다(isolated node가 없다고 가정).
모든 $\bx\in\R^n$에 대해 $$\bx^\top\mathbf L\bx=\sum_{(u,v)\in E}(x_u-x_v)^2,\qquad\bx^\top\mathbf L_{\text{sym}}\bx=\sum_{(u,v)\in E}\Big(\frac{x_u}{\sqrt{d_u}}-\frac{x_v}{\sqrt{d_v}}\Big)^2.$$ (합은 각 undirected edge를 한 번씩 센다.) 따라서 $\mathbf L,\mathbf L_{\text{sym}}$은 positive semidefinite이고, $\mathbf L_{\text{sym}}$의 eigenvalue는 $[0,2]$에 있다.
$\bx^\top\mathbf D\bx=\sum_vd_vx_v^2=\sum_{(u,v)\in E}(x_u^2+x_v^2)$이고 $\bx^\top\bA\bx=2\sum_{(u,v)\in E}x_ux_v$이므로 첫 식이 나온다. 둘째 식은 $\bx=\mathbf D^{-1/2}\mathbf y$를 넣으면 같다. Eigenvalue의 상한은 $(a-b)^2\le2a^2+2b^2$로부터 $\bx^\top\mathbf L_{\text{sym}}\bx\le2\sum_{(u,v)\in E}\big(\frac{x_u^2}{d_u}+\frac{x_v^2}{d_v}\big)=2\|\bx\|^2$이다.
$\bx^\top\mathbf L\bx$는 신호 $\bx$가 edge를 따라 얼마나 급하게 변하는지, 즉 graph 위에서의 "거칠기"를 잰다(Dirichlet energy). $\mathbf L_{\text{sym}}=\mathbf U\boldsymbol\Lambda\mathbf U^\top$로 eigendecomposition하면, eigenvalue가 작은 eigenvector는 이웃끼리 비슷한 값을 갖는 저주파 신호이고 큰 eigenvalue는 고주파 신호이다. $\mathbf U^\top\bx$를 graph Fourier transform이라 하고, convolution theorem을 흉내 내 spectral filter를 $$g_\theta\star\bx=\mathbf U\,g_\theta(\boldsymbol\Lambda)\,\mathbf U^\top\bx$$ 로 정의한다(Bruna et al., 2014). 그러나 eigendecomposition은 $O(n^3)$이고 filter가 localize되지 않는다. $g_\theta$를 $K$차 polynomial $\sum_{k=0}^K\theta_k\boldsymbol\Lambda^k$로 제한하면 $g_\theta\star\bx=\sum_k\theta_k\mathbf L_{\text{sym}}^k\bx$로 eigendecomposition이 필요 없고, $(\mathbf L^k)_{uv}$는 $u,v$의 거리가 $k$보다 크면 0이므로 filter가 $K$-hop 안에서만 작용한다(ChebNet; Defferrard et al., 2016).
GCN은 $K=1$로 두고 더 단순화한 것이다. $\mathbf L_{\text{sym}}$의 최대 eigenvalue를 2로 근사해 $[-1,1]$로 rescale한 1차 filter는 $\theta_0\bx+\theta_1(\mathbf L_{\text{sym}}-\bI)\bx=\theta_0\bx-\theta_1\mathbf D^{-1/2}\bA\mathbf D^{-1/2}\bx$이다. Parameter를 하나로 묶어 $\theta=\theta_0=-\theta_1$로 두면 $\theta(\bI+\mathbf D^{-1/2}\bA\mathbf D^{-1/2})\bx$가 된다. 이 행렬의 eigenvalue는 $[0,2]$에 있어서 layer를 반복해 곱하면 값이 폭발하거나 사라질 수 있다. 그래서 self-loop를 먼저 더한 뒤 정규화하는 renormalization trick $\bI+\mathbf D^{-1/2}\bA\mathbf D^{-1/2}\to\tilde{\mathbf D}^{-1/2}\tilde\bA\tilde{\mathbf D}^{-1/2}=\hat\bA$를 쓴다. $\hat\bA$의 eigenvalue는 $(-1,1]$에 있다(아래 over-smoothing 절에서 증명한다). 여러 channel의 feature와 weight 행렬로 일반화한 것이 위의 GCN layer이다.
즉 GCN의 한 layer는 "이웃끼리 feature를 평균 내는 low-pass filter + 공유 linear 변환 + non-linearity"이다. Cora 같은 citation graph에서 2-layer GCN이 label 몇 개만으로 높은 정확도를 내는 이유는, 연결된 논문끼리 분야가 같다는 성질(homophily)이 강하기 때문이다. 이웃끼리 label이 다른 heterophily graph에서는 이런 smoothing이 오히려 해가 된다.
11.5GraphSAGE와 Graph attention network
GCN의 $\hat\bA$는 고정된 graph 전체에 대해 정의되므로, 새 node나 새 graph에 적용하기 어렵고 큰 graph에서는 전체 행렬 곱이 비싸다. GraphSAGE(Hamilton et al., 2017)는 자기 feature와 이웃 aggregate를 이어 붙인다. $$\bh_v^{(l+1)}=\sigma\Big(\bW^{(l)}\big[\bh_v^{(l)}\,\big\|\,\mathrm{AGG}\big(\{\bh_u^{(l)}:u\in\mathcal S(v)\}\big)\big]\Big),$$ $\|$는 concatenation, AGG는 mean, max-pooling, LSTM 등이고 $\mathcal S(v)$는 $\mathcal N(v)$에서 고정된 개수만큼 sampling한 이웃이다. Layer마다 이웃 수를 제한하므로 mini-batch로 학습할 수 있고, weight가 graph와 무관하므로 처음 보는 node에도 적용할 수 있다(inductive).
GCN은 이웃마다 degree로 정해진 고정 weight를 준다. Graph attention network(GAT; Veličković et al., 2018)는 Chapter 8의 attention처럼 weight를 data에서 계산한다. $$e_{vu}=\mathrm{LeakyReLU}\big(\ba^\top[\bW\bh_v\,\|\,\bW\bh_u]\big),\qquad\alpha_{vu}=\frac{\exp(e_{vu})}{\sum_{k\in\mathcal N(v)\cup\{v\}}\exp(e_{vk})},\qquad\bh_v'=\sigma\Big(\sum_{u\in\mathcal N(v)\cup\{v\}}\alpha_{vu}\bW\bh_u\Big).$$ Transformer의 self-attention에서 softmax의 범위를 graph의 이웃으로 제한(masking)한 것과 같고, 여러 head를 써서 이어 붙이거나 평균 낸다. Transformer는 모든 node가 연결된 complete graph 위의 GAT라고 볼 수 있으며, 반대로 graph의 구조를 positional encoding(Laplacian eigenvector, random walk 확률 등)으로 넣은 Transformer를 graph transformer라 한다.
11.6표현력: Weisfeiler–Lehman test
두 graph가 구조적으로 같은지(isomorphic) 판정하는 문제에는 다항시간 algorithm이 알려져 있지 않다. 고전적인 heuristic이 1-dimensional Weisfeiler–Lehman test(1-WL, color refinement)이다.
- 모든 node에 같은 color $c_v^{(0)}$를 준다(node feature가 있으면 그것으로).
- repeat: $c_v^{(t+1)}=\mathrm{HASH}\big(c_v^{(t)},\ \{\!\{c_u^{(t)}:u\in\mathcal N(v)\}\!\}\big)$ ($\{\!\{\cdot\}\!\}$는 multiset, HASH는 injective)
- until color 분할이 더 이상 바뀌지 않음
- 두 graph의 color histogram이 다르면 "non-isomorphic", 같으면 "판정 불가"
이 과정은 message passing과 구조가 같다. HASH 자리에 학습되는 함수가 들어간 것이 GNN이다. 따라서 다음이 성립한다.
(a) 1-WL이 구분하지 못하는 두 graph는 어떤 message passing GNN(Definition 11.2)도 구분하지 못한다(같은 readout output을 낸다).
(b) Aggregation $\bigoplus$와 update $\varphi$, readout이 모두 multiset 위에서 injective이면 GNN은 1-WL만큼 강력하다.
(a)의 예가 위 그림의 두 triangle과 6-cycle이다. 모든 node의 degree가 2이므로 1-WL에서 color가 한 번도 갈라지지 않는다. Triangle의 개수 같은 간단한 구조적 성질도 message passing만으로는 셀 수 없다는 뜻이다.
(b)에서 aggregation의 선택이 중요해진다. Mean은 이웃 multiset $\{a,b\}$와 $\{a,a,b,b\}$를 구분하지 못하고(분포만 본다), max는 $\{a,b\}$와 $\{a,a,b\}$도 구분하지 못한다(집합만 본다). Sum은 countable feature 공간에서 적절한 feature 변환 뒤에 multiset을 injective하게 표현할 수 있다. 이에 근거한 graph isomorphism network(GIN)는 $$\bh_v^{(l+1)}=\mathrm{MLP}^{(l)}\Big((1+\epsilon^{(l)})\,\bh_v^{(l)}+\sum_{u\in\mathcal N(v)}\bh_u^{(l)}\Big)$$ 이다. 1-WL의 한계를 넘으려면 node에 구조적 정보를 추가로 준다. 각 node가 속한 cycle의 수 같은 substructure count, Laplacian eigenvector나 random walk 기반의 positional encoding, 또는 node 쌍이나 부분 graph 단위로 message를 주고받는 higher-order GNN이 그 방법이다.
11.7Over-smoothing과 over-squashing
CNN은 수십, 수백 층을 쌓지만 GCN은 2–3층에서 성능이 가장 좋고 더 깊으면 나빠지는 경우가 많다. 이유 중 하나가 over-smoothing이다. GCN의 propagation을 반복하면 모든 node의 feature가 같아진다.
$G$가 connected이면 $\hat\bA=\tilde{\mathbf D}^{-1/2}\tilde\bA\tilde{\mathbf D}^{-1/2}$의 eigenvalue는 $1=\lambda_1>\lambda_2\ge\cdots\ge\lambda_n>-1$이고, $\lambda_1$의 eigenvector는 $\bu=\tilde{\mathbf D}^{1/2}\mathbf 1/\|\tilde{\mathbf D}^{1/2}\mathbf 1\|$이다. 따라서 임의의 $\bX$에 대해 $$\hat\bA^k\bX\to\bu\bu^\top\bX\qquad(k\to\infty),\qquad\big\|\hat\bA^k\bX-\bu\bu^\top\bX\big\|\le\lambda_\ast^k\,\big\|\bX-\bu\bu^\top\bX\big\|,\quad\lambda_\ast=\max(|\lambda_2|,|\lambda_n|)\lt1.$$ 극한에서 node $v$의 feature는 $\sqrt{\tilde d_v}$에 비례하는 같은 vector가 되어, node 사이의 차이가 degree 말고는 남지 않는다.
$\hat\bA=\tilde{\mathbf D}^{1/2}\big(\tilde{\mathbf D}^{-1}\tilde\bA\big)\tilde{\mathbf D}^{-1/2}$이므로 $\hat\bA$는 random walk transition matrix $\mathbf T=\tilde{\mathbf D}^{-1}\tilde\bA$와 similar하고 eigenvalue가 같다. $\mathbf T$는 row 합이 1인 stochastic matrix이고, $G$가 connected이므로 irreducible, self-loop가 있으므로 aperiodic이다. Perron–Frobenius theorem에 의해 eigenvalue 1은 simple이고 나머지 eigenvalue의 절댓값은 1보다 작다. $\mathbf T\mathbf 1=\mathbf 1$이므로 $\hat\bA\tilde{\mathbf D}^{1/2}\mathbf 1=\tilde{\mathbf D}^{1/2}\mathbf T\mathbf 1=\tilde{\mathbf D}^{1/2}\mathbf 1$. $\hat\bA$는 symmetric이므로 $\hat\bA=\sum_i\lambda_i\bu_i\bu_i^\top$로 orthogonal하게 분해되고, $\hat\bA^k-\bu\bu^\top=\sum_{i\ge2}\lambda_i^k\bu_i\bu_i^\top$이 $\bu^\perp$ 위에서 operator norm $\lambda_\ast^k$를 갖는다.
실제 GCN에는 layer마다 $\bW^{(l)}$와 non-linearity가 있으므로 이 명제가 그대로 적용되지는 않지만, weight가 크지 않으면 feature 사이의 차이(Dirichlet energy)가 layer마다 지수적으로 줄어든다는 결과가 알려져 있다(Oono & Suzuki, 2020). 대응책은 CNN에서 배운 것과 비슷하다. Residual connection(초기 feature를 각 layer에 다시 더하는 GCNII 등), layer마다 feature의 평균과 분산을 조정하는 normalization(PairNorm), 모든 layer의 output을 모아 쓰는 jumping knowledge 등이다.
또 다른 한계는 over-squashing이다(Alon & Yahav, 2021). 멀리 떨어진 node의 정보가 $L$-hop 안의 기하급수적으로 많은 node를 거쳐 고정 크기의 vector 하나에 압축되어야 하므로, graph의 병목(bottleneck) 구조를 통과하는 장거리 의존성을 학습하기 어렵다. RNN이 긴 sequence를 hidden state 하나에 압축하면서 겪던 문제(Chapter 7)와 같은 구조이고, 해법도 비슷하게 graph를 rewiring하거나 전역 attention(graph transformer)을 더하는 것이다.
11.8학습과 응용
Node classification. Label이 있는 node 집합 $V_L$에 대해서만 cross-entropy $-\sum_{v\in V_L}\log p_\theta(y_v\mid G)_v$를 계산한다. Forward pass는 graph 전체를 쓰므로 label 없는 node도 이웃으로서 학습에 기여한다.
Link prediction. Node embedding $\bh_u,\bh_v$로 edge 확률을 $\sigma(\bh_u^\top\bh_v)$ 같은 score로 model하고, 관측된 edge를 positive, 무작위 node 쌍을 negative로 하는 binary cross-entropy로 학습한다. Chapter 7의 word2vec negative sampling(Theorem 7.2)과 같은 구조이다. 단어의 co-occurrence가 edge로 바뀐 것이다.
Graph classification. 크기가 다른 여러 graph를 mini-batch로 묶을 때는 adjacency matrix를 block-diagonal로 쌓아 하나의 큰 (연결되지 않은) graph로 만든다. Message passing은 block 안에서만 일어나고, readout은 graph별로 따로 한다. 분자 data에서는 원자 종류와 결합 종류가 node, edge feature이다.
기하학적 대칭. 원자의 3차원 좌표나 point cloud를 다룰 때는 permutation뿐 아니라 회전과 평행이동에 대해서도 equivariant해야 한다. 좌표 자체 대신 node 사이의 거리처럼 회전에 불변인 양을 message에 쓰거나, 좌표를 equivariant하게 update하는 E(n)-equivariant GNN(Satorras et al., 2021) 등이 단백질 구조 예측과 분자 생성의 기반이 되었다.
Representation Learning
Chapter 12Representation, Transfer, Foundation Model
Lecture Week 03 (5–6), Week 05 (6. MAE), Week 10, Week 13–14 (Augmentation, KD)
Chapter 2에서 network를 encoder와 classifier로 나누었다. 좋은 encoder는 한 task에만 쓸모 있는 것이 아니라 다른 task로 옮겨 쓸 수 있다. 이 장은 label 없이 좋은 representation을 배우는 self-supervised learning, 배운 encoder를 새 task에 맞추는 transfer learning과 fine-tuning(LoRA 포함), 그리고 이 둘이 결합된 foundation model을 다룬다. 학습 데이터를 늘리고 지식을 옮기는 data augmentation과 knowledge distillation도 함께 정리한다.
12.1Representation이란
Encoder $E:\R^{3\times224\times224}\to\R^D$는 고차원 input을 저차원 vector로 보내는 dimension reduction이다. Classification을 잘하는 model이란 image와 label을 잘 mapping하는 function이고, 이는 encoder가 image에서 label과 관련 높은 feature들만 잘 추출했다는 뜻이다.
이를 뒷받침하는 가정이 manifold hypothesis이다. 실제 data는 고차원 공간 전체에 퍼져 있지 않고 훨씬 낮은 차원의 manifold 근처에 몰려 있다. $224\times224$ 공간에서 random하게 뽑은 점은 거의 모두 noise로 보이고, 자연 image는 그중 극히 작은 부분집합이다. Encoder는 이 manifold의 좌표계를 배우는 것으로 볼 수 있으며, 그 좌표 공간을 representation space(latent space, feature space)라 한다. t-SNE나 UMAP으로 representation을 2차원에 그려 보면 같은 class끼리 모여 있는지 확인할 수 있다.
Manifold 관점은 "두 data 사이의 중간"이 무엇인지도 바꾼다. 골프 스윙의 두 frame을 pixel 공간에서 선형 보간(linear interpolation)하면 두 image가 반투명하게 겹친 이상한 image가 나온다. 반면 manifold 위에서, 즉 잘 학습된 representation 공간에서 보간한 뒤 다시 image로 돌리면 실제로 그 사이 동작을 하는 자연스러운 frame이 나온다(manifold interpolation). 좋은 representation 공간에서는 의미 있는 변화가 단순한 기하학적 이동으로 표현된다. Word embedding의 vector 연산(Chapter 7)도 같은 현상이다.
Representation의 품질은 보통 linear probe로 잰다. Encoder를 고정하고 그 위에 linear classifier만 학습해 accuracy를 본다. Linear classifier로 잘 분리된다면 encoder가 필요한 정보를 linearly separable한 형태로 정리해 두었다는 뜻이다.
12.2Supervised, self-supervised, unsupervised
| Paradigm | Data | Target | 예 |
|---|---|---|---|
| Supervised | $(X,Y)$ | 사람이 붙인 label $y$ | Classification, detection(box+label), segmentation(label image) |
| Self-supervised | $X$ | Data에서 자동으로 만든 pseudo-label | Rotation 예측, jigsaw, contrastive, masked modeling |
| Unsupervised | $X$ | Label 없음, objective만 있음 | Clustering, PCA, autoencoder, VAE |
Self-supervised learning(SSL)은 data 자체에서 정답을 만들어 supervised learning처럼 학습한다. 사람이 정한 pretext task를 풀면서 encoder가 유용한 representation을 배우기를 기대한다. Label 비용 없이 대량의 data를 쓸 수 있다는 것이 핵심 장점이다.
12.3Pretext task의 초기 예
Rotation prediction(Gidaris et al., 2018): image를 0°, 90°, 180°, 270° 중 하나로 돌리고 몇 도 돌렸는지 4-class classification을 한다. 물체가 무엇이고 어느 쪽이 위인지 알아야 풀 수 있으므로 semantic feature를 배우게 된다. Jigsaw puzzle(Noroozi & Favaro, 2016): image를 $3\times3$ patch로 자르고 섞은 뒤 원래의 배치(미리 정한 permutation 집합 중 하나)를 맞힌다. 둘 다 효과는 있었지만, task를 사람이 설계해야 하고 그 task에 특화된 feature를 배운다는 한계가 있었다.
12.4Contrastive learning
Contrastive learning은 "같은 image에서 나온 두 view는 가깝게, 다른 image의 view는 멀게"라는 일반적인 원리로 representation을 배운다.
Mini-batch의 image $N$개 각각에 random augmentation $t,t'\sim\mathcal T$(crop, color jitter, blur 등)를 적용해 $2N$개의 view를 만든다. Encoder $f$와 projection head $g$(작은 MLP)로 $\bh=f(\tilde\bx)$, $\bz=g(\bh)$를 계산하고, 같은 image에서 나온 쌍 $(i,j)$에 대해 $$\ell_{i,j}=-\log\frac{\exp(\mathrm{sim}(\bz_i,\bz_j)/\tau)}{\sum_{k=1}^{2N}\ind_{[k\ne i]}\exp(\mathrm{sim}(\bz_i,\bz_k)/\tau)},\qquad\mathrm{sim}(\mathbf u,\mathbf v)=\frac{\mathbf u^\top\mathbf v}{\|\mathbf u\|\|\mathbf v\|}$$ 를 모든 positive 쌍(양방향)에 대해 평균한 것을 loss로 한다(NT-Xent). $\tau$는 temperature이다.
이 loss는 $2N-1$개 후보 중 positive를 고르는 $(2N-1)$-class cross-entropy이다. Negative가 많을수록 과제가 어려워지므로 큰 batch(4096 등)가 성능에 중요하다. 학습 후에는 projection head $g$를 버리고 $\bh=f(\bx)$를 representation으로 쓴다. $g$의 output은 augmentation에 불변이 되도록 강하게 압축되어 downstream에 필요한 정보(색, 방향 등)까지 잃기 때문이다. Linear evaluation에서 SimCLR는 supervised pre-training과 비슷한 성능을 보였고, 여러 dataset으로의 transfer에서도 경쟁력이 있었다.
이 objective의 통계적 의미는 mutual information과 연결된다.
Positive 하나와 negative $N-1$개로 구성된 InfoNCE loss $\L_N$에 대해 $$I(\bx;\bx')\ge\log N-\L_N.$$ 따라서 InfoNCE를 minimize하는 것은 두 view 사이의 mutual information의 lower bound를 maximize하는 것이다.
(개요) Anchor $\bx$에 대해 positive $\bx'_1\sim p(\bx'\mid\bx)$ 하나와 negative $\bx'_2,\dots,\bx'_N\iid p(\bx')$를 두고, critic $f(\bx,\bx')=\exp(s(\bx,\bx'))$로 $$\L_N=-\E\Big[\log\frac{f(\bx,\bx'_1)}{\sum_{j=1}^Nf(\bx,\bx'_j)}\Big]$$ 라 하자. 이는 $N$개 중 positive를 맞히는 categorical cross-entropy이고, Bayes rule로 계산한 posterior가 최적 classifier이므로 optimal critic은 $f^\ast(\bx,\bx')\propto p(\bx'\mid\bx)/p(\bx')$이다. 이를 대입하면 $$\L_N^{\text{opt}}=\E\Big[\log\Big(1+\frac{p(\bx'_1)}{p(\bx'_1\mid\bx)}\sum_{j=2}^N\frac{p(\bx'_j\mid\bx)}{p(\bx'_j)}\Big)\Big]\approx\E\Big[\log\Big(1+\frac{p(\bx'_1)}{p(\bx'_1\mid\bx)}(N-1)\Big)\Big]\gtrsim\E\Big[\log\frac{p(\bx'_1)}{p(\bx'_1\mid\bx)}N\Big]=-I(\bx;\bx')+\log N.$$ 첫 근사는 negative에 대한 합을 그 기댓값 $(N-1)\E_{p(\bx')}[p(\bx'\mid\bx)/p(\bx')]=N-1$로 바꾼 것이다(큰 $N$에서 정당화된다). 둘째 부등식은 $1+a(N-1)\ge aN\iff a\le1$을 쓴 것으로, $a=p(\bx'_1)/p(\bx'_1\mid\bx)$는 positive 쌍에서 대체로 1보다 작다. 이 유도는 van den Oord et al.의 원래 논증으로 엄밀하지 않다. 임의의 critic의 loss는 optimal critic의 loss 이상이므로 $\L_N\ge\L_N^{\text{opt}}\gtrsim\log N-I$, 즉 $I\gtrsim\log N-\L_N$이다. Bound 자체는 근사 없이 엄밀하게 성립하며, 그 증명은 Poole et al.(2019)에 있다.
Bound가 $\log N$을 넘을 수 없으므로 negative가 많을수록 더 큰 MI를 표현할 수 있다는 점도 큰 batch를 정당화한다. MoCo(He et al., 2020)는 큰 batch 대신 과거 batch의 key를 queue에 저장해 negative로 재사용하고, key encoder를 $\theta_k\leftarrow m\theta_k+(1-m)\theta_q$의 momentum update로 천천히 바꿔 queue 안의 key들이 일관되게 유지되도록 한다.
Supervised contrastive learning
Label이 있다면 "같은 class는 모두 positive"로 확장할 수 있다. Anchor $i$와 같은 label을 가진 다른 sample 집합을 $P(i)$, 자기 자신을 뺀 전체를 $A(i)$라 할 때 $$\L^{\text{sup}}=\sum_i\frac{-1}{|P(i)|}\sum_{p\in P(i)}\log\frac{\exp(\bz_i^\top\bz_p/\tau)}{\sum_{a\in A(i)}\exp(\bz_i^\top\bz_a/\tau)}$$ 이다(SupCon; Khosla et al., 2020). 원 논문은 이렇게 학습한 encoder 위에 linear classifier를 얹는 것이 cross-entropy로 바로 학습하는 것보다 성능이 좋고, hyperparameter와 data corruption에 더 robust하다고 보고했다. 이 식은 positive들에 대한 평균을 log 바깥에 둔 형태($\L^{\text{sup}}_{\text{out}}$)이고, 평균을 log 안에 넣은 형태 $$\L^{\text{sup}}_{\text{in}}=\sum_i-\log\Big\{\frac{1}{|P(i)|}\sum_{p\in P(i)}\frac{\exp(\bz_i^\top\bz_p/\tau)}{\sum_{a\in A(i)}\exp(\bz_i^\top\bz_a/\tau)}\Big\}$$ 도 가능하다. $-\log$의 convexity와 Jensen's inequality에 의해 $\L^{\text{sup}}_{\text{in}}\le\L^{\text{sup}}_{\text{out}}$이며, 논문은 $\L_{\text{out}}$ 쪽이 학습이 더 안정적이고 성능이 좋다고 보고했다.
Triplet loss
Contrastive learning의 더 오래된 형태로, anchor $\bx_a$, 같은 class의 positive $\bx_p$, 다른 class의 negative $\bx_n$ 세 개를 한 묶음으로 $$\L_{\text{triplet}}=\max\big(0,\ \|f(\bx_a)-f(\bx_p)\|^2-\|f(\bx_a)-f(\bx_n)\|^2+m\big)$$ 를 minimize한다(FaceNet; Schroff et al., 2015). Negative가 positive보다 margin $m$ 이상 멀어지면 loss가 0이다. 한 번에 negative 하나만 보므로, 쉬운 negative가 대부분이면 학습 신호가 약해 어려운 negative를 골라 주는 hard negative mining이 필요하다. InfoNCE는 많은 negative를 softmax로 한꺼번에 비교해 이 문제를 완화한 것으로 볼 수 있다.
12.5Negative 없이 배우기: non-contrastive SSL
Contrastive learning은 큰 batch나 queue로 많은 negative를 확보해야 한다. 그런데 negative는 왜 필요한가? 두 view의 representation을 가깝게 만드는 것만이 목적이라면 모든 input을 같은 vector로 보내는 상수 함수 $f(\bx)\equiv\mathbf c$가 loss를 최소화한다. 이를 representation collapse라 한다. Negative는 이를 막는 장치이다. Wang & Isola(2020)는 이 역할을 정확히 분해했다.
Representation이 단위 구면 위에 있을 때($\|f(\bx)\|=1$), negative 수 $N\to\infty$에서 InfoNCE에서 $\log N$을 뺀 값은 $$-\frac1\tau\E_{(\bx,\bx^+)}\big[f(\bx)^\top f(\bx^+)\big]+\E_{\bx}\Big[\log\E_{\bx^-}\big[e^{f(\bx)^\top f(\bx^-)/\tau}\big]\Big]$$ 로 수렴한다. 첫 항은 positive 쌍을 가깝게 하는 alignment, 둘째 항은 representation이 구면 위에 고르게 퍼지게 하는 uniformity이다.
Uniformity 항이 collapse를 막는다. 그렇다면 negative 없이 다른 방법으로 이 역할을 할 수 있을까? 세 가지 방향이 있다.
비대칭 구조: BYOL과 SimSiam
BYOL(Grill et al., 2020)은 두 network를 쓴다. Online network는 encoder $f_\theta$, projector $g_\theta$, 그리고 추가로 predictor $q_\theta$를 갖고, target network는 같은 구조의 encoder와 projector $f_\xi,g_\xi$만 갖는다. Online이 한 view에서 target의 다른 view representation을 예측하도록 $$\L_{\text{BYOL}}=\Big\|\frac{q_\theta(\bz_\theta)}{\|q_\theta(\bz_\theta)\|}-\frac{\bz'_\xi}{\|\bz'_\xi\|}\Big\|^2=2-2\cos\big(q_\theta(\bz_\theta),\bz'_\xi\big),\qquad\bz_\theta=g_\theta(f_\theta(\bx)),\ \bz'_\xi=g_\xi(f_\xi(\bx'))$$ 를 $\theta$에 대해서만 최소화하고(두 view를 바꾼 항을 더해 대칭화한다), target은 gradient를 받지 않고 exponential moving average(EMA) $\xi\leftarrow\tau\xi+(1-\tau)\theta$ ($\tau\approx0.996$)로만 따라간다. MoCo의 momentum encoder와 같은 장치이다.
SimSiam(Chen & He, 2021)은 더 단순화해서 target network를 따로 두지 않고 같은 encoder를 쓰되, target 쪽 branch에서 gradient만 끊는다(stop-gradient). $$\L_{\text{SimSiam}}=-\frac12\cos\big(\bp_1,\mathrm{sg}(\bz_2)\big)-\frac12\cos\big(\bp_2,\mathrm{sg}(\bz_1)\big),\qquad\bp_i=h(\bz_i),\ \bz_i=f(\bx_i).$$ 실험 결과 EMA, 큰 batch, negative가 없어도 되지만 stop-gradient를 빼면 즉시 collapse한다. 저자들은 이를 EM과 비슷한 교대 최적화로 해석했다. 각 image의 "평균 representation" $\eta_\bx=\E_{\mathcal T}[f(\mathcal T(\bx))]$를 latent variable로 보고, $\eta$를 고정한 채 $f$를 update하는 것과 $f$를 고정하고 $\eta$를 다시 계산하는 것을 번갈아 하는데, stop-gradient가 그 고정을 구현한다는 것이다. Predictor가 이 기댓값(augmentation에 대한 평균)을 근사하는 역할을 한다. Linear network에서는 predictor의 eigenspace가 representation의 correlation matrix와 정렬되면서 collapse가 아닌 고정점으로 간다는 분석도 있다(Tian et al., 2021).
통계량으로 막기: Barlow Twins와 VICReg
Collapse를 representation의 통계량에 대한 명시적 penalty로 막을 수도 있다. Batch에서 두 view의 representation $\bZ,\bZ'\in\R^{B\times k}$를 얻는다고 하자. Barlow Twins(Zbontar et al., 2021)는 차원별로 batch 방향 standardize한 뒤 cross-correlation matrix $\mathbf C_{ij}=\frac1B\sum_b z_{bi}z'_{bj}$를 identity에 가깝게 만든다. $$\L_{\text{BT}}=\sum_i(1-\mathbf C_{ii})^2+\lambda\sum_{i\ne j}\mathbf C_{ij}^2.$$ 대각항은 같은 차원끼리의 invariance를, 비대각항은 차원 사이의 redundancy 제거(decorrelation)를 요구한다. VICReg(Bardes et al., 2022)는 세 항을 분리한다. $$\L=\lambda\,\frac1B\sum_b\|\bz_b-\bz'_b\|^2+\mu\big[v(\bZ)+v(\bZ')\big]+\nu\big[c(\bZ)+c(\bZ')\big],$$ $$v(\bZ)=\frac1k\sum_{j=1}^k\max\Big(0,\ \gamma-\sqrt{\Var(z_{\cdot j})+\epsilon}\Big),\qquad c(\bZ)=\frac1k\sum_{i\ne j}\big[\Cov(\bZ)\big]_{ij}^2.$$ Invariance 항은 positive 쌍을 가깝게, variance 항은 각 차원의 standard deviation이 $\gamma$($=1$) 아래로 내려가지 않게(collapse 방지), covariance 항은 차원 사이의 공분산을 0으로 만든다(정보가 몇 차원에 몰리는 dimensional collapse 방지). Contrastive loss의 uniformity가 sample 사이를 밀어내는 것이라면, 이 방법들은 차원 사이의 공분산 구조를 직접 whitening 쪽으로 미는 것이다. 통계학의 언어로는 representation의 second moment를 제약하는 것이다.
Self-distillation: DINO
DINO(Caron et al., 2021; self-distillation with no labels)는 knowledge distillation(이 장 마지막 절)을 label 없이 한다. Student $g_{\theta_s}$와 teacher $g_{\theta_t}$는 같은 구조(ViT + projection head)이고, 각각 $K$차원(예: 65,536) output에 temperature softmax를 적용한다. $$P_s(\bx)=\softmax\big(g_{\theta_s}(\bx)/\tau_s\big),\qquad P_t(\bx)=\softmax\big((g_{\theta_t}(\bx)-\mathbf c)/\tau_t\big),\qquad\min_{\theta_s}\sum_{\bx\in\{\bx_1^g,\bx_2^g\}}\ \sum_{\bx'\ne\bx}H\big(P_t(\bx),P_s(\bx')\big).$$ Teacher는 image의 큰 영역을 담은 global crop 두 개만, student는 global crop과 작은 local crop 여러 개를 모두 본다(multi-crop). 작은 부분만 보고 전체 image에 대한 teacher의 판단을 맞혀야 하므로 local-to-global 대응을 배운다. Teacher는 EMA로만 update된다. Collapse를 막는 장치는 두 가지이다.
- Centering. Teacher output에서 batch 평균의 EMA $\mathbf c\leftarrow m\mathbf c+(1-m)\frac1B\sum_bg_{\theta_t}(\bx_b)$를 뺀다. 한 차원이 모든 input에서 지배하는 collapse를 막지만, 혼자 쓰면 모든 출력이 uniform distribution으로 가는 반대 방향의 collapse를 부추긴다.
- Sharpening. Teacher temperature를 student보다 낮게 둔다($\tau_t\approx0.04$–$0.07$, $\tau_s=0.1$). Teacher distribution이 뾰족해져 uniform collapse를 막는다.
둘은 반대 방향으로 작용하며 균형을 이룬다. DINO로 학습한 ViT의 class token attention map은 label 없이도 물체의 윤곽을 따라 나뉘는 성질을 보였다. DINOv2(Oquab et al., 2024)는 여기에 MAE식 masked token 예측 loss(iBOT), 자동으로 중복을 제거하고 균형을 맞춘 1억 4천만 장 규모의 curated dataset, 그리고 batch 안의 representation이 고르게 퍼지게 하는 KoLeo regularizer $$\L_{\text{KoLeo}}=-\frac1B\sum_{i=1}^B\log\Big(\min_{j\ne i}\|\bz_i-\bz_j\|\Big)$$ 를 더했다. 이는 nearest-neighbor 거리로 differential entropy를 추정하는 Kozachenko–Leonenko estimator에서 나온 것으로, representation 분포의 entropy를 키워 uniformity를 주는 항이다. 1B parameter 규모의 ViT-g를 학습한 뒤 작은 model로 distillation해 배포했고, fine-tuning 없이 frozen feature에 linear layer만 얹어도 classification, segmentation, depth 추정에서 강한 성능을 내는 범용 vision backbone이 되었다. Label이 적은 domain에서 pre-trained backbone으로 널리 쓰인다.
12.6Masked autoencoder
Contrastive 방식이 view 사이의 판별로 배운다면, masked modeling은 가려진 부분을 복원하며 배운다(generative SSL). NLP에서 BERT가 문장의 15% token을 가리고 맞히는 방식으로 성공한 것을 vision에 옮긴 것이 MAE(He et al., 2022)이다.
- Image를 ViT처럼 patch로 자르고 75%를 random하게 가린다.
- Encoder(ViT)는 보이는 25% patch만 처리한다. Token 수가 1/4이므로 계산이 크게 줄어든다.
- 가벼운 decoder가 encoder output과 가려진 위치의 mask token(+position embedding)을 받아 모든 patch의 pixel을 복원한다.
- Loss는 가려진 patch에 대해서만 계산한 pixel MSE이다.
Image는 language보다 중복이 많아 주변 pixel로 쉽게 채울 수 있으므로, 75%라는 높은 masking 비율이 있어야 의미 있는 task가 된다. MAE pre-training 후 fine-tuning하면 ViT를 ImageNet-1k만으로도 잘 학습할 수 있고, 여러 domain의 foundation model이 MAE를 pre-training 방법으로 채택했다.
Latent 공간에서 예측하기: JEPA
MAE는 가려진 patch의 pixel을 복원하므로, 질감이나 noise처럼 예측할 수 없고 의미와도 무관한 세부까지 맞히려고 capacity를 쓴다. I-JEPA(Assran et al., 2023; joint-embedding predictive architecture)는 pixel 대신 representation을 예측한다. Image의 한 context block을 context encoder에 넣고, predictor가 같은 image의 다른 target block들의 representation을 예측하게 한다. Target representation은 EMA로 update되는 target encoder가 만든다. Loss는 예측과 target representation 사이의 $\ell_2$ 거리이다. BYOL의 비대칭 구조(EMA target, predictor)와 MAE의 masking을 결합한 형태로, hand-crafted augmentation 없이도 의미 수준의 representation을 배운다.
| 계열 | 대표 방법 | Collapse를 막는 장치 | 학습 신호 |
|---|---|---|---|
| Contrastive | SimCLR, MoCo, CLIP | Negative (uniformity) | Positive와 negative의 판별 |
| 비대칭 network | BYOL, SimSiam | Predictor + stop-gradient (+EMA) | 다른 view의 representation 예측 |
| Redundancy reduction | Barlow Twins, VICReg | Variance·covariance penalty | Cross-correlation을 identity로 |
| Self-distillation | DINO, DINOv2 | Centering + sharpening, EMA teacher | Teacher의 soft output 맞히기 |
| Masked modeling | MAE, BERT | (복원 target이 있어 collapse 없음) | 가려진 pixel/token 복원 |
| Latent prediction | I-JEPA | EMA target + predictor | 가려진 영역의 representation 예측 |
12.7Transfer learning과 fine-tuning
Encoder를 처음부터 학습하려면 큰 dataset과 계산 자원이 필요하다. 그래서 보통 big tech나 연구 그룹이 대규모 data로 학습해 공개한 pre-trained encoder에서 출발해, 내 task에 맞게 조금 변형한다. 이때 task(classification → segmentation)와 domain(natural image → 다른 종류의 image, text → signal)을 모두 바꿀 수 있다.
| Strategy | 학습하는 것 | 특징 |
|---|---|---|
| Linear probe (transfer learning) | 새 classifier만 | 가장 싸고 overfitting에 강함. Representation 품질을 그대로 반영 |
| Partial fine-tuning | 마지막 몇 block + classifier | 앞 layer의 일반적 feature는 유지 |
| Full fine-tuning | 모든 parameter | 보통 성능이 가장 좋음. Data가 적으면 overfitting, model마다 전체 복사본 필요 |
| LoRA 등 PEFT | 추가한 작은 module만 | Full fine-tuning에 가까운 성능, 저장·memory 비용 작음 |
용어상 encoder를 그대로 고정해 쓰는 것을 transfer learning, encoder까지 추가 학습하는 것을 fine-tuning이라 구분하기도 하지만 실무에서는 구분 없이 섞어 쓴다.
Pre-trained weight $\bW_0\in\R^{d\times k}$를 고정하고, 학습되는 low-rank 행렬 $\mathbf B\in\R^{d\times r}$, $\mathbf A\in\R^{r\times k}$ ($r\ll\min(d,k)$)를 더한다. $$\bh=\bW_0\bx+\frac{\alpha}{r}\mathbf B\mathbf A\bx.$$ $\mathbf A$는 random Gaussian, $\mathbf B=\mathbf 0$으로 초기화해 학습 시작 시점에 원래 model과 정확히 같게 한다.
Update $\Delta\bW=\mathbf B\mathbf A$의 rank를 $r$ 이하로 제한하는 것이다. 학습 parameter 수는 $dk$에서 $r(d+k)$로 줄어든다. 예를 들어 $d=k=4096$, $r=8$이면 약 1,680만 개가 65,536개(0.4%)가 된다. 이 설계는 "fine-tuning에서 필요한 weight 변화는 intrinsic rank가 낮다"는 관찰에 근거한다. 절약되는 것은 주로 frozen weight의 gradient와 optimizer state(Adam은 parameter마다 moment 두 개를 저장한다)의 memory이다. Activation에 대한 backpropagation 자체는 여전히 전체 network를 거쳐야 한다. 학습 후 $\bW=\bW_0+\frac\alpha r\mathbf B\mathbf A$로 합쳐 두면 inference 비용은 원래 model과 같다. Transformer처럼 큰 model에서 특히 유용하며, task마다 작은 $(\mathbf A,\mathbf B)$만 저장하면 된다.
12.8Foundation model
대규모의 넓은 data로 (주로 self-supervision을 통해) 학습되어, 다양한 downstream task에 adaptation될 수 있는 model. 많은 응용이 그 위에 세워지는 "토대"라는 뜻이다.
BERT 하나를 sentiment analysis, QA, 번역에 조금씩 고쳐 쓰는 것이 전형적인 예이다. Vision에서는 MAE, DINOv2, CLIP이, time series에서는 공개 data를 모은 Time-series Pile로 학습한 MOMENT(Goswami et al., 2024) 같은 model이 있다.
MOMENT(ICML 2024)는 time series에서 foundation model을 만들 때의 세 가지 어려움, 즉 (1) 크고 통합된 공개 data가 없고, (2) dataset마다 sampling rate, channel 수, 길이, 진폭이 제각각이며, (3) 평가 benchmark가 부족하다는 문제를 다룬다. 공개 time series를 모은 Time-series Pile(약 20GB, 1,300만 개 series, 12.3억 timestamp)을 만들고, 길이를 고정한 series를 patch로 잘라 일부를 가린 뒤 복원하는 masked modeling(MAE와 같은 방식)으로 Transformer를 pre-training했다. Forecasting, classification, anomaly detection, imputation을 linear probing 또는 zero-shot으로 평가하며, classification은 고정된 representation 위에 SVM을 학습하는 식이다. 관찰된 결과 몇 가지: classification과 imputation에서 가장 좋았고, model이 클수록 training loss가 낮았으며(GPT와 같은 scaling 경향), language model weight로 초기화하는 것이 random 초기화보다 나을 것이 없었다. 즉 Time-series Pile이 그 자체로 충분한 pre-training data였다. Sinusoid에 trend, 진폭, 주파수 변화를 준 합성 data의 representation을 t-SNE로 보면 대부분의 변화가 잘 분리되지만, baseline shift는 input normalization 때문에 구분되지 않았다.
Domain foundation model에서 자주 쓰는 설계는 일반 data(예: ImageNet)로 먼저 self-supervised pre-training을 하고, 같은 방법으로 target domain의 대량 unlabeled data에 이어서 pre-training(continued pre-training)한 뒤 소량의 label로 fine-tuning하는 것이다. Domain data가 적을수록 앞 단계가 큰 도움이 된다. Foundation model을 연구에 쓰는 절차는 대체로 다음과 같다.
- Task 정의: input modality, output 형태, 평가 지표를 정한다.
- SOTA 탐색: 해당 modality와 task의 최신 model과 공개 weight를 찾는다(논문의 GitHub, benchmark leaderboard).
- Adaptation 방법 결정: data 양과 계산 자원에 따라 linear probe, fine-tuning, LoRA 중 고른다. Label efficiency(fine-tuning data 양을 줄여 가며 성능을 보는 실험)는 foundation model 논문의 표준 평가 항목이다.
12.9Multimodal: CLIP
CLIP(Radford et al., 2021)은 인터넷에서 모은 4억 개의 (image, caption) 쌍으로 image encoder $f$와 text encoder $g$를 함께 학습한다. Batch의 $N$개 쌍에 대해 정규화된 embedding $\mathbf I_i=f(\text{img}_i)/\|f(\cdot)\|$, $\mathbf T_j=g(\text{txt}_j)/\|g(\cdot)\|$로 $N\times N$ 유사도 행렬 $S_{ij}=\mathbf I_i^\top\mathbf T_j/\tau$를 만들고, $$\L=\frac12\Big[\frac1N\sum_i\mathrm{CE}(\mathbf S_{i,:},i)+\frac1N\sum_j\mathrm{CE}(\mathbf S_{:,j},j)\Big]$$ 즉 row 방향(image→text)과 column 방향(text→image)의 cross-entropy를 평균한다. 대각선이 positive인 symmetric InfoNCE이다.
학습이 끝나면 두 modality가 같은 공간에 놓이므로 zero-shot classification이 가능하다. Class 이름으로 "a photo of a {class}" 같은 prompt를 만들어 text embedding을 구하고, image embedding과 cosine similarity가 가장 큰 class를 고른다. 해당 dataset으로 한 번도 학습하지 않고도 ImageNet에서 ResNet-50 supervised 수준의 accuracy를 보였다. CLIP의 text encoder는 Chapter 18의 text-to-image diffusion에서 조건 입력으로 쓰인다.
12.10Data augmentation
Augmentation은 label을 바꾸지 않는 변환 $t$로 data를 늘려, model이 $f(t(\bx))\approx f(\bx)$라는 invariance를 배우게 한다. 기본적인 것은 random crop, flip, rotation 같은 geometric 변환과 brightness, contrast, color jitter 같은 photometric 변환이다. 주요 방법을 분류하면 다음과 같다.
| 분류 | 방법 |
|---|---|
| Image manipulation | Flip, rotation, scaling, crop, aspect ratio, brightness, blur, noise |
| Image erasing | Cutout, random erasing, grid mask: 일부 영역을 지워 가려진 물체도 인식하게 함 |
| Image mixing | Mixup, CutMix, sample pairing (아래) |
| Automated augmentation | AutoAugment, Fast AutoAugment, RandAugment |
| Feature augmentation | Feature 공간에서 섞기(FeatMatch, moment exchange 등) |
| Generative model 기반 | GAN, diffusion으로 새 sample 생성 (Part IV) |
AutoAugment(Cubuk et al., 2019)는 어떤 변환을 어떤 확률과 강도로 쓸지를 reinforcement learning으로 search했지만 비용이 매우 컸다. RandAugment(Cubuk et al., 2020)는 search 없이 변환 목록에서 $N$개를 무작위로 골라 공통 강도 $M$으로 적용하며, hyperparameter가 $(N,M)$ 두 개뿐인데도 비슷한 성능을 낸다.
Mixup과 CutMix
두 sample을 섞어 새 sample을 만드는 방법도 있다. Mixup(Zhang et al., 2018)은 $\lambda\sim\mathrm{Beta}(\alpha,\alpha)$에 대해 $$\tilde\bx=\lambda\bx_i+(1-\lambda)\bx_j,\qquad\tilde\by=\lambda\by_i+(1-\lambda)\by_j.$$ Cross-entropy는 label에 대해 linear이므로 soft label $\tilde\by$에 대한 CE는 $$\mathrm{CE}(f(\tilde\bx),\tilde\by)=\lambda\,\mathrm{CE}(f(\tilde\bx),\by_i)+(1-\lambda)\,\mathrm{CE}(f(\tilde\bx),\by_j)$$ 로 쓸 수 있고, 구현에서는 이 형태를 쓴다. Sample 사이를 linear하게 행동하도록 유도하는 regularization이다. CutMix(Yun et al., 2019)는 pixel을 섞는 대신 $\bx_j$의 직사각형 영역을 잘라 $\bx_i$에 붙인다. Binary mask $\mathbf M$에 대해 $\tilde\bx=\mathbf M\odot\bx_i+(\mathbf 1-\mathbf M)\odot\bx_j$이고, $\lambda$는 실제로 남은 $\bx_i$의 면적 비율로 정한다. 자연스러운 local 구조를 유지하므로 localization 성능에도 도움이 된다.
12.11Knowledge distillation
크고 정확한 teacher model의 지식을 작은 student model로 옮기는 방법이다(Hinton et al., 2015). Teacher의 softmax output은 정답 class 외에도 "이 고양이 사진은 개와 조금 닮았고 자동차와는 전혀 닮지 않았다" 같은 class 간 유사성 정보(dark knowledge)를 담고 있다. 이를 드러내기 위해 temperature $T$로 softmax를 부드럽게 한다. $$p_k^{(T)}=\frac{\exp(z_k/T)}{\sum_j\exp(z_j/T)}.$$ Student logit $\mathbf z^s$, teacher logit $\mathbf z^t$에 대해 loss는 $$\L_{\text{KD}}=(1-\alpha)\,\mathrm{CE}\big(\by,\mathbf p^{s,(1)}\big)+\alpha\,T^2\,\KL\big(\mathbf p^{t,(T)}\,\big\|\,\mathbf p^{s,(T)}\big)$$ 이다. $T^2$를 곱하는 이유는 soft target 항의 logit gradient가 $\frac1T(\mathbf p^{s,(T)}-\mathbf p^{t,(T)})$이고, $T$가 크면 이것이 대략 $\frac{1}{T^2}$로 작아지기 때문이다. $T^2$로 보정해야 $T$를 바꿔도 두 항의 상대적 비중이 유지된다.
Chapter 13Interpretability: Gradient 기반 Attribution
Lecture Week 07 (Explainability, CAM, GradCAM)
Linear regression에서는 추정된 $\hat\beta_j$가 곧 $j$번째 변수의 중요도이다. Deep network는 non-linear layer가 겹겹이 쌓인 black box이고, pixel 하나는 그 자체로 의미가 없다. 이 장에서는 학습이 끝난 model의 개별 예측을 사후적으로(post-hoc) 설명하는 gradient 기반 방법들, 즉 saliency map, guided backpropagation, CAM, Grad-CAM을 정리하고 그 한계를 짚는다.
13.1무엇을 설명하는가
Conventional machine learning에서는 input의 각 차원이 사람이 정의한 feature이고 model이 얕으므로, fitted coefficient가 바로 해석된다. Deep learning은 raw data를 받고, 깊은 non-linear 구조 때문에 개별 weight에서 의미를 읽을 수 없다. 설명의 대상은 크게 두 가지이다.
- Model의 decision: 이 input에 대해 왜 이 output을 냈는가? Input의 어느 부분이 결정에 기여했는가?
- Training process: model이 data에서 무엇을 배웠는가? 어떤 shortcut(예: image 구석의 watermark, 촬영 장비 차이)을 이용하고 있지는 않은가?
이 장의 방법들은 첫 번째에 해당하며, 결과는 input과 같은 shape의 attribution map(heatmap)이다. 같은 도구로 두 번째 질문, 특히 dataset bias를 찾는 데도 쓸 수 있다. 예를 들어 서로 다른 출처의 image를 구분하는 model이 내용이 아니라 출처마다 다른 촬영 조건을 보고 있다면 heatmap이 엉뚱한 곳을 가리킨다.
13.2Input에 대한 gradient: saliency map
Training에서는 loss를 parameter로 미분했다. Input $\bx$는 상수였다. 설명에서는 반대로 parameter를 고정하고 class score $y^c$(softmax 이전 logit)를 input으로 미분한다. $$\mathbf S^c=\frac{\partial y^c}{\partial\bx}\in\R^{C\times H\times W}.$$ First-order Taylor 근사 $y^c(\bx+\Delta)\approx y^c(\bx)+\mathbf S^{c\top}\Delta$에서 보듯, $|\mathbf S^c|$가 큰 pixel은 조금만 바뀌어도 class score가 크게 바뀌는 pixel이다(Simonyan et al., 2014). Backpropagation을 parameter에서 멈추지 않고 input까지 한 단계 더 진행하면 얻어진다. 다만 gradient는 국소적 민감도일 뿐이고 결과가 noisy하다. 또 ReLU network에서 이미 saturate된 feature(값을 조금 바꿔도 output이 변하지 않는 feature)는 결정에 크게 기여했더라도 gradient가 0일 수 있다.
이를 보완한 것이 integrated gradients(Sundararajan et al., 2017)이다. 기준점(baseline) $\bx'$(예: 검은 image)에서 $\bx$까지 직선 경로를 따라 gradient를 적분한다. $$\mathrm{IG}_j(\bx)=(x_j-x'_j)\int_0^1\frac{\partial y^c}{\partial x_j}\big(\bx'+t(\bx-\bx')\big)\,\dd t.$$ 경로 $\gamma(t)=\bx'+t(\bx-\bx')$에 대해 미적분학의 기본정리를 쓰면 $y^c(\bx)-y^c(\bx')=\int_0^1\nabla y^c(\gamma(t))^\top\gamma'(t)\,\dd t=\sum_j\mathrm{IG}_j(\bx)$이다. 즉 attribution의 합이 정확히 baseline 대비 output의 변화량과 같다(completeness). Linear model $y=\bw^\top\bx$이면 $\mathrm{IG}_j=w_j(x_j-x'_j)$로, regression coefficient에 의한 기여 분해와 일치한다.
13.3Guided backpropagation
ReLU $f^{l+1}=\max(0,f^l)$에서 backward signal $R^{l+1}=\partial y^c/\partial f^{l+1}$이 아래로 전달되는 규칙을 바꿔 saliency를 선명하게 만드는 방법들이 있다.
| Method | ReLU에서의 backward rule |
|---|---|
| Backpropagation (gradient) | $R^l=\ind[f^l>0]\cdot R^{l+1}$ forward에서 음수였던 위치를 막음 |
| Deconvnet | $R^l=\ind[R^{l+1}>0]\cdot R^{l+1}$ 음수 gradient를 막음 |
| Guided backpropagation | $R^l=\ind[f^l>0]\cdot\ind[R^{l+1}>0]\cdot R^{l+1}$ 둘 다 막음 |
Guided backpropagation(Springenberg et al., 2015)은 class score를 증가시키는 방향의 신호만 통과시키므로 물체의 윤곽이 선명한 고해상도 map을 준다. 대신 class를 잘 구분하지 못한다(class-discriminative하지 않다). 고양이 class로 계산하든 개 class로 계산하든 비슷한 map이 나오는 경우가 많다.
13.4Class activation map
마지막 convolution layer의 feature map $A^k\in\R^{u\times v}$ ($k=1,\dots,K$ channel) 뒤에 GAP와 linear classifier만 있는 구조를 생각하자. $$F_k=\sum_{i,j}A^k_{ij},\qquad y^c=\sum_k w_k^cF_k.$$ (GAP의 $1/Z$, $Z=uv$는 상수이므로 $w$에 흡수했다.) 합의 순서를 바꾸면 $$y^c=\sum_{i,j}\underbrace{\sum_kw_k^cA^k_{ij}}_{M^c_{ij}}.$$
$M^c_{ij}=\sum_kw_k^cA^k_{ij}$를 class $c$의 class activation map이라 한다. Class score는 정확히 $y^c=\sum_{i,j}M^c_{ij}$이므로 $M^c_{ij}$는 공간 위치 $(i,j)$가 class $c$의 score에 기여한 양이다.
$M^c$는 $u\times v$ 해상도(예: $7\times7$)이므로 input 크기로 upsampling(interpolation)해 원본 image 위에 겹쳐 그린다. CAM은 class마다 다른 weight $w^c$를 쓰므로 class-discriminative하다. 한계는 구조 제약이다. 마지막이 반드시 GAP + linear layer여야 하므로, 다른 구조의 model에는 구조를 바꿔 다시 학습해야 한다.
13.5Grad-CAM
Grad-CAM(Selvaraju et al., 2017)은 CAM의 weight $w_k^c$를 재학습 없이 gradient로 대신 계산한다.
임의의 CNN의 (보통 마지막) convolution feature map $A^k$에 대해 $$\alpha_k^c=\frac1Z\sum_{i,j}\frac{\partial y^c}{\partial A^k_{ij}},\qquad L^c_{\text{Grad-CAM}}=\mathrm{ReLU}\Big(\sum_k\alpha_k^cA^k\Big).$$ $\alpha_k^c$는 channel $k$가 class $c$의 결정에 얼마나 중요한지를 나타내는 weight이고, ReLU는 class score를 높이는 쪽의 영향만 남긴다.
Model이 CAM 구조 $y^c=\sum_kw_k^c\frac1Z\sum_{i,j}A^k_{ij}$이면 $\alpha_k^c=w_k^c/Z$이고, 따라서 $L^c_{\text{Grad-CAM}}=\frac1Z\mathrm{ReLU}(M^c)$이다. 즉 positive scaling과 ReLU를 제외하면 Grad-CAM은 CAM과 같다.
$\partial y^c/\partial A^k_{ij}=w_k^c/Z$가 모든 $(i,j)$에서 같으므로 $\alpha_k^c=\frac1Z\sum_{i,j}w_k^c/Z=w_k^c/Z$. 대입하면 $\sum_k\alpha_k^cA^k=\frac1Z\sum_kw_k^cA^k=\frac1ZM^c$.
Classifier 부분이 어떤 구조이든(여러 층의 MLP, captioning이나 VQA의 head 등) gradient만 계산할 수 있으면 적용할 수 있다. Output의 shape은 activation map과 같으므로 시각화 때는 input 해상도로 resize한다.
Guided Grad-CAM
Grad-CAM은 class-discriminative하지만 해상도가 낮고, guided backpropagation은 해상도가 높지만 class-discriminative하지 않다. 둘을 곱하면 장점을 합칠 수 있다. 예를 들어 Grad-CAM이 $10\times10$, input이 $50\times50$이면 Grad-CAM을 $50\times50$으로 upsampling한 뒤 guided backpropagation map과 element-wise로 곱한다. Grad-CAM이 일종의 mask 역할을 해서 해당 class와 관련된 영역의 세밀한 윤곽만 남긴다.
13.6그 밖의 설명 방법
Occlusion map(Zeiler & Fergus, 2014)은 gradient를 쓰지 않는다. Input의 일부를 회색 patch로 가리고 class score가 얼마나 떨어지는지를 위치마다 계산한다. 직관적이고 model 구조와 무관하지만, patch 크기에 따라 결과가 달라지고 위치마다 forward pass가 필요해 비싸다.
Counterfactual explanation은 "input이 어떻게 바뀌었다면 결정이 바뀌었을까"를 보여 준다. 예를 들어 나이를 예측하는 model에 대해 generative model로 얼굴을 최소한으로 바꿔 예측이 달라지게 만든 image를 보여 주면, model이 어떤 특징(주름, 머리색 등)을 근거로 쓰는지 드러난다. Heatmap이 "어디"를 보여 준다면 counterfactual은 "무엇이 달라야 하는가"를 보여 준다.
Language로 설명하기. LLM에게 답만 묻지 않고 중간 추론 과정을 쓰게 하는 chain-of-thought prompting(Wei et al., 2022)은 정확도를 높일 뿐 아니라 답에 이른 과정을 사람이 검토할 수 있게 한다. 다만 생성된 추론이 model 내부의 실제 계산을 충실히 반영한다는 보장은 없으므로, 이것도 attribution map과 같은 sanity check의 관점으로 봐야 한다. 설명 가능한 AI(XAI)의 목표는 사용자가 "왜 그렇게 했는지, 언제 성공하고 언제 실패하는지, 언제 믿어도 되는지"를 알 수 있게 하는 것이다.
13.7한계와 sanity check
Attribution map은 보기에 그럴듯해도 model을 충실히 반영한다는 보장이 없다. Adebayo et al.(2018)은 두 가지 sanity check를 제안했다. (1) Model weight를 random으로 바꿨을 때 map이 달라져야 하고, (2) label을 random하게 섞어 학습한 model에서도 map이 달라져야 한다. Guided backpropagation은 두 검사 모두에서 map이 거의 변하지 않았다. 즉 model이 무엇을 배웠는지보다 input image의 edge 구조를 보여 주는 것에 가깝다. Gradient와 Grad-CAM은 검사를 통과했다.
또한 image가 아닌 data에서는 heatmap의 해석이 어렵다. 1D 신호에서 "이 구간이 중요하다"는 표시만으로는 부족하고, peak의 위치나 주파수 성분처럼 그 domain의 언어로 다시 해석해야 하는 경우가 많다. 최근에는 vision–language model로 판단 근거를 자연어로 설명하게 하는 시도도 늘고 있다.
Chapter 14Label이 적거나 틀렸거나 치우쳤을 때
새로 추가한 장 (강의 범위 밖). Sohn et al. 2020; Patrini et al. 2017; Ghosh et al. 2017; Menon et al. 2021; Gal et al. 2017
교과서의 예제는 label이 충분하고, 정확하고, class가 고르게 분포한다. 실제 data는 셋 다 아닌 경우가 많다. Label을 붙이는 데 전문가의 시간이 들어 일부만 label이 있고, 사람이 붙인 label에는 오류가 섞이며, 관심 있는 class(이상, 질병, 사기)는 드물다. 이 장은 세 문제를 통계적 model로 정식화하고 대응법을 유도한다. Label 없는 data를 쓰는 semi-supervised learning, label noise의 모형화와 보정, class imbalance에서의 decision rule, 그리고 어떤 data에 label을 붙일지 고르는 active learning이다. Chapter 12의 self-supervised pre-training이 첫 번째 문제에 대한 가장 강력한 답이라는 점은 미리 말해 둔다. 이 장의 방법은 그 위에서 함께 쓰인다.
14.1Semi-supervised learning
Label이 있는 $\{(\bx_i,y_i)\}_{i=1}^n$과 label이 없는 $\{\bx_j\}_{j=1}^m$ ($m\gg n$)이 있을 때, unlabeled data는 $p(\bx)$에 대한 정보만 준다. 그것이 $p(y\mid\bx)$를 배우는 데 도움이 되려면 두 distribution 사이에 연결이 있어야 한다. 대표적인 가정은 다음과 같다.
- Cluster assumption: 같은 cluster(고밀도 영역으로 연결된 점들)의 점은 같은 class이다. 동치로, decision boundary는 저밀도 영역을 지나야 한다(low-density separation).
- Manifold assumption: data는 저차원 manifold 근처에 있고, label은 manifold를 따라 매끄럽게 변한다.
이 가정이 틀리면 unlabeled data는 도움이 되지 않거나 오히려 해가 된다. 고전적인 예로 class별 Gaussian mixture를 EM으로 fit하면 unlabeled data로 mixture를 정확히 추정할 수 있지만, model이 틀리면(misspecification) unlabeled data가 많을수록 decision boundary가 잘못된 쪽으로 끌려간다.
Entropy minimization과 pseudo-labeling
Low-density separation을 loss로 쓰는 가장 직접적인 방법은 unlabeled data에서 예측의 entropy $H(p_\theta(\cdot\mid\bx_j))$를 줄이는 것이다(Grandvalet & Bengio, 2005). 모든 unlabeled 점에서 확신 있게 예측하려면 boundary가 그 점들에서 멀리, 즉 저밀도 영역을 지나야 하기 때문이다. Pseudo-labeling(Lee, 2013)은 그 hard 버전이다. 현재 model이 확신하는 unlabeled sample에 예측 class를 label로 붙여 학습 data에 넣는다(self-training). 위험은 초기의 틀린 예측이 스스로를 강화하는 confirmation bias이므로, 확신도 threshold와 점진적인 추가가 중요하다.
Consistency regularization과 FixMatch
또 다른 원리는 input을 조금 바꿔도 예측이 같아야 한다는 것이다. 같은 unlabeled input의 두 augmentation, 또는 student와 EMA teacher(Mean Teacher; Tarvainen & Valpola, 2017. Chapter 12의 BYOL·DINO와 같은 장치)의 예측 차이를 penalty로 준다. FixMatch(Sohn et al., 2020)는 두 원리를 결합한 단순한 방법이다. $$\L=\frac1B\sum_{b}\mathrm{CE}\big(y_b,p_\theta(\cdot\mid\alpha(\bx_b))\big)+\lambda_u\frac1{\mu B}\sum_{j}\ind\Big[\max_c\hat q_{jc}\ge\tau\Big]\,\mathrm{CE}\big(\hat y_j,p_\theta(\cdot\mid\mathcal A(\bx_j))\big),$$ $\hat\bq_j=p_\theta(\cdot\mid\alpha(\bx_j))$는 약한 augmentation $\alpha$(flip, crop)에 대한 예측이고 $\hat y_j=\argmax_c\hat q_{jc}$이다. 확신도가 $\tau$(0.95)를 넘는 unlabeled sample만 pseudo-label을 만들고, 그 label을 강한 augmentation $\mathcal A$(RandAugment, Cutout)를 적용한 input에서 맞히게 한다. 쉬운 view에서 얻은 확신을 어려운 view로 전파하는 것이다. CIFAR-10에서 class당 25개, 총 250개의 label만으로 약 95%의 정확도를 냈다. 실무에서는 self-supervised pre-training(Chapter 12) 후 적은 label로 fine-tuning하는 것이 가장 강력한 출발점이고, 그 위에 pseudo-labeling이나 consistency를 더하는 경우가 많다.
14.2Label noise
Label 오류는 생각보다 흔하다. 널리 쓰이는 benchmark의 test set에서도 평균 3% 이상의 label 오류가 발견되었다(Northcutt et al., 2021). 통계적으로 가장 단순한 model은 class-conditional noise이다. 관측된 label $\tilde y$가 진짜 label $y$에만 의존하고 $\bx$와는 조건부 독립이라 가정하고, noise transition matrix를 $$T_{ij}=P(\tilde y=j\mid y=i)$$ 로 정의한다. 그러면 noisy posterior는 $p(\tilde y=j\mid\bx)=\sum_iT_{ij}\,p(y=i\mid\bx)$, 즉 $\tilde\bp(\bx)=\mathbf T^\top\bp(\bx)$이다.
$\mathbf T$가 invertible이면, noisy label에 대해 $$\L_{\text{fwd}}(\theta)=\E_{(\bx,\tilde y)}\Big[-\log\big(\mathbf T^\top\bp_\theta(\bx)\big)_{\tilde y}\Big]$$ 를 (충분히 유연한 model class에서) 최소화하는 $\bp_\theta(\bx)$는 진짜 posterior $p(y\mid\bx)$이다.
각 $\bx$에서 $\E_{\tilde y\mid\bx}[-\log\mathbf r_{\tilde y}]$를 확률 vector $\mathbf r$에 대해 최소화하면 cross-entropy가 proper scoring rule(Chapter 21)이므로 $\mathbf r=\tilde\bp(\bx)=\mathbf T^\top\bp(\bx)$이다. $\mathbf r=\mathbf T^\top\bp_\theta(\bx)$이므로 $\mathbf T^\top\bp_\theta=\mathbf T^\top\bp$이고, $\mathbf T$가 invertible이면 $\bp_\theta=\bp$.
즉 model의 clean 예측에 noise 과정을 덧씌운 뒤 noisy label과 비교하면, model 자체는 clean posterior를 배운다. 3-class 합성 예(class 0의 40%가 class 1로, class 2의 20%가 class 1로 바뀌는 비대칭 noise, 전체 오류율 20%)에서 보통의 cross-entropy로 학습한 MLP의 clean test 정확도는 0.688이었고, forward correction을 쓰면 0.776으로 Bayes 정확도 0.779에 거의 도달했다. $\mathbf T$는 보통 모르므로 추정해야 한다. 진짜 class가 거의 확실한 anchor sample $\bx^{(i)}$($p(y=i\mid\bx^{(i)})\approx1$)를 찾으면 $\tilde\bp(\bx^{(i)})\approx\mathbf T_{i,:}$이므로, noisy data로 학습한 classifier에서 class별로 가장 확신하는 sample의 예측을 모아 $\mathbf T$의 row를 추정한다.
Noise에 강건한 loss
$\mathbf T$를 추정하지 않고 loss 자체를 바꾸는 방법도 있다. Label noise가 모든 다른 class로 균등하게 퍼지는 symmetric noise(rate $\eta$)를 생각하자.
Loss가 모든 $f$에 대해 $\sum_{k=1}^K\ell(f(\bx),k)=C$(상수)를 만족하면, symmetric noise 아래의 risk는 $$R_\eta(f)=\Big(1-\frac{\eta K}{K-1}\Big)R(f)+\frac{\eta C}{K-1}$$ 이다. 따라서 $\eta\lt(K-1)/K$이면 noisy risk의 minimizer와 clean risk의 minimizer가 같다.
$R_\eta(f)=\E\big[(1-\eta)\ell(f(\bx),y)+\frac\eta{K-1}\sum_{k\ne y}\ell(f(\bx),k)\big]=\E\big[(1-\eta)\ell(f,y)+\frac\eta{K-1}(C-\ell(f,y))\big]$를 정리한다. 계수가 양수이면 $R_\eta$는 $R$의 증가함수이다.
Softmax 출력에 대한 MAE $\|\bp-\be_y\|_1=2(1-p_y)$는 이 조건을 만족하지만 cross-entropy는 만족하지 않는다. CE는 틀린 label의 sample에 큰 gradient를 주어 noise를 외우게 된다. 대신 MAE는 학습이 느리므로 둘을 절충한 generalized cross-entropy $(1-p_y^q)/q$(Zhang & Sabuncu, 2018)가 쓰인다($q\to0$이면 CE, $q=1$이면 MAE).
Memorization의 시간 구조
Chapter 5에서 network는 random label도 외울 수 있음을 보았다. 그런데 외우는 데는 시간이 걸린다. Noisy label이 섞인 data로 학습하면 network는 먼저 깨끗한 sample에서 일반적인 pattern을 배우고, 나중에야 틀린 label을 외운다(Arpit et al., 2017). 그래서 학습 초기에 loss가 작은 sample은 깨끗할 가능성이 높다. 두 network가 서로 상대의 loss가 작은 sample로만 학습하는 co-teaching(Han et al., 2018), 학습 초기 예측을 target으로 삼아 외우기를 막는 방법, 그리고 early stopping이 모두 이 관찰에 기대고 있다. Data 정리 관점에서는 cross-validation 예측과 주어진 label이 크게 어긋나는 sample을 찾아 다시 검토하는 것(confident learning)이 가장 실용적이다.
14.3Class imbalance
Class prior $\pi_y=P(Y=y)$가 크게 치우친 경우, 문제는 학습 자체보다 "무엇을 최적화하는가"에 있다. 보통의 cross-entropy로 학습한 calibrated model의 $\argmax_yp(y\mid\bx)$는 전체 정확도(standard error)를 최소화하는 Bayes classifier이다. 그런데 드문 class를 놓치는 것이 문제라면 관심 있는 것은 class별 오류의 평균인 balanced error $\frac1K\sum_yP(\hat Y\ne y\mid Y=y)$이다.
Balanced error를 최소화하는 classifier는 $$\hat y(\bx)=\argmax_yp(\bx\mid y)=\argmax_y\frac{p(y\mid\bx)}{\pi_y}=\argmax_y\big(f_y(\bx)-\log\pi_y\big)$$ 이다. 여기서 $f_y$는 $p(y\mid\bx)\propto e^{f_y(\bx)}$인 logit이다.
Balanced error는 class prior를 균등($1/K$)으로 바꾼 distribution에서의 0-1 risk이다. 그 distribution의 posterior는 $p(\bx\mid y)\cdot\frac1K/\sum$이므로 Bayes classifier는 $\argmax_yp(\bx\mid y)$이다. Bayes rule $p(\bx\mid y)=p(y\mid\bx)p(\bx)/\pi_y$에서 $p(\bx)$는 $y$와 무관하다.
이 결과는 두 가지 구현으로 이어진다(Menon et al., 2021). (1) Post-hoc 보정: 보통대로 학습한 뒤 예측할 때 logit에서 $\tau\log\pi_y$를 뺀다($\tau=1$이 위 정리). Model을 다시 학습할 필요가 없다. (2) Logit-adjusted loss: 학습 때 logit에 $\tau\log\pi_y$를 더한 $\mathrm{CE}(y,\softmax(\mathbf f+\tau\log\boldsymbol\pi))$를 쓰고, 예측 때는 원래 logit $\mathbf f$를 쓴다. 학습 중 흔한 class가 prior 덕분에 "공짜로" 얻는 점수를 미리 반영해, model이 class별 likelihood ratio에 해당하는 부분만 배우게 한다. Chapter 22의 cost 기반 threshold와 같은 결정이론의 결과이며, Chapter 23의 label shift 보정과도 같은 식이다.
그 밖의 방법들도 같은 틀로 볼 수 있다. Class 가중치 $w_y\propto1/\pi_y$로 loss를 reweighting하거나 드문 class를 oversampling하는 것은 기대값에서 같은 objective(균등 prior)를 최적화하지만, 큰 weight 때문에 분산이 크고 over-parameterized network에서는 학습 data를 외워 버리면 효과가 사라지는 경향이 있다. Focal loss $-(1-p_y)^\gamma\log p_y$(Lin et al., 2017)는 이미 잘 맞힌 쉬운 sample의 비중을 줄인다. 평가에서는 accuracy 대신 balanced accuracy, class별 recall, PR curve(Chapter 22)를 보고해야 한다. 그리고 앞의 정리처럼 decision threshold의 선택은 학습과 분리해서, 원하는 error 기준과 배포 환경의 prior에 맞춰 정하는 것이 원칙이다.
14.4Active learning
Label 예산이 정해져 있을 때 어떤 sample에 label을 붙일지를 model이 고르는 것이 active learning이다. Pool-based 설정에서는 label 없는 pool에서 acquisition function $a(\bx)$가 가장 큰 sample(들)을 골라 label을 받고, model을 다시 학습하는 과정을 반복한다.
- Uncertainty sampling: 예측 entropy $H(p_\theta(\cdot\mid\bx))$나 margin(1등과 2등 확률의 차이)이 큰 sample을 고른다.
- BALD(Houlsby et al., 2011; Gal et al., 2017): Chapter 21의 epistemic uncertainty, 즉 $I(y;\theta\mid\bx,\mathcal D)=H(\bar\bp)-\E_\theta H(\bp_\theta)$가 큰 sample을 고른다. MC dropout이나 ensemble로 계산한다. Label이 본질적으로 모호한 sample(aleatoric)은 피하고, model이 몰라서 불확실한 sample에 집중한다.
- Diversity: 한 번에 여러 개를 고를 때 비슷한 sample만 뽑지 않도록, feature 공간을 고르게 덮는 core-set(Sener & Savarese, 2018)이나 불확실성과 다양성을 결합한 방법을 쓴다.
주의할 점은 통계적이다. Active learning으로 모은 labeled set은 model이 고른 편향된 sample이므로, 그 위에서 계산한 성능은 전체 분포의 성능을 추정하지 않는다. 평가용 test set은 반드시 무작위로 따로 뽑아야 한다. 또 처음에 label이 거의 없을 때는 model의 불확실성 추정 자체가 부정확해서 random sampling보다 나빠지기도 한다(cold start). Pre-trained representation 위에서 시작하면 이 문제가 크게 줄어든다.
14.5정리
| 문제 | 통계적 model | 핵심 대응 |
|---|---|---|
| Label 부족 | $p(\bx)$와 $p(y\mid\bx)$의 연결(cluster, manifold 가정) | SSL pre-training, FixMatch, pseudo-label |
| Label 오류 | Noise transition $\mathbf T$, $\tilde\bp=\mathbf T^\top\bp$ | Forward correction, 강건한 loss, 초기 학습 신호 이용, data 정리 |
| Class imbalance | Prior $\pi_y$와 목표 error의 불일치 | Logit adjustment, threshold 선택, 적절한 metric |
| Label 예산 | 정보량이 큰 sample 선택 | BALD, diversity, 무작위 test set 유지 |
Generative Models
Chapter 15Generative Model과 Variational Autoencoder
Lecture Week 09, Week 11 (+ handwritten notes), Week 13 (VAE review)
지금까지의 model은 $p_\theta(y\mid\bx)$, 즉 input이 주어졌을 때 label의 distribution을 배웠다. Generative model은 data 자체의 distribution $p_\theta(\bx)$를 배우고, 거기서 새 sample을 뽑는다. 이 장에서는 latent variable model의 likelihood가 왜 계산 불가능한지 보고, 이를 variational inference로 우회하는 variational autoencoder(VAE)를 ELBO 유도부터 reparameterization trick까지 정리한다.
15.1Discriminative vs generative
Discriminative model은 $p(y\mid\bx)$를 직접 model하며, 지금까지 다룬 classifier가 모두 여기에 속한다. Generative model은 $p(\bx)$ 또는 $p(\bx,y)$를 model한다. Data $\bx_1,\dots,\bx_n\iid p_{\text{data}}$가 주어졌을 때 목표는 $$\theta^\ast=\argmax_\theta\sum_{i=1}^n\log p_\theta(\bx_i)=\argmin_\theta\KL(\hat p_{\text{data}}\,\|\,p_\theta)$$ 이다(Chapter 3의 MLE–KL 관계, data가 이산적이면 정확히 성립). 그리고 학습된 $p_\theta$에서 sample을 뽑을 수 있어야 한다. 문제는 image처럼 고차원이고 복잡한 distribution을 어떤 family로 표현하고, 그 likelihood를 어떻게 계산하느냐이다.
| Discriminative | Generative | |
|---|---|---|
| Model하는 것 | $p(y\mid\bx)$, decision boundary | $p(\bx,y)=p(\bx\mid y)p(y)$ 또는 $p(\bx)$ |
| Classification | 직접 $p(y\mid\bx)$를 출력 | Bayes rule $p(y\mid\bx)\propto p(\bx\mid y)p(y)$로 계산 |
| 새 data 생성 | 불가 | 가능 |
| 예 | Logistic regression, SVM, random forest, decision tree, kNN, 대부분의 neural network classifier | Naive Bayes, Gaussian discriminant analysis(LDA/QDA), Gaussian mixture, HMM, Bayesian network, VAE, GAN, diffusion, GPT |
통계학의 LDA는 class별로 $\bx\mid y=k\sim\N(\bmu_k,\bSigma)$를 가정한 generative classifier이고, 이때 $p(y\mid\bx)$는 정확히 logistic(softmax) 형태가 된다. 같은 decision boundary를 discriminative하게 직접 fit한 것이 logistic regression이다. Classification 성능만 보면 보통 discriminative model이 낫지만, generative model은 data 전체의 구조를 배우므로 생성, 결측 복원, 이상치 탐지가 가능하다.
15.2Autoencoder
Autoencoder(AE)는 encoder $e_\phi$와 decoder $d_\theta$로 input을 복원한다. $$\min_{\phi,\theta}\sum_i\|\bx_i-d_\theta(e_\phi(\bx_i))\|^2,\qquad\bz=e_\phi(\bx)\in\R^{d_z},\ d_z\ll\dim\bx.$$ $\bz$는 $\bx$의 차원축소된 latent vector이며, encoder는 decoder가 복원할 때 필요한 정보를 남기는 방향으로 압축해야 한다. Activation이 없는 linear AE를 MSE로 학습하면 최적 decoder가 span하는 공간은 PCA의 상위 $d_z$개 principal component가 span하는 공간과 같다(Baldi & Hornik, 1989). AE는 non-linear PCA인 셈이다.
AE의 목적은 encoder, 즉 압축과 차원축소이다. 학습된 decoder에 아무 $\bz$나 넣으면 의미 있는 image가 나오지 않는다. Latent 공간에서 training data의 code가 어디에 놓일지 아무 제약이 없어서, code 사이의 빈 공간이 decoder에게는 한 번도 본 적 없는 영역이기 때문이다. 생성을 하려면 latent 공간에 distribution을 부여해야 한다.
15.3Latent variable model
단순한 prior $p(\bz)=\N(\mathbf 0,\bI)$에서 $\bz$를 뽑고, decoder가 정하는 conditional $p_\theta(\bx\mid\bz)$에서 $\bx$를 뽑는 model을 생각한다. $\bz$는 생성을 조종하는 controller 역할을 하며, 단순할수록 sampling이 쉽다. Marginal likelihood는 $$p_\theta(\bx)=\int p_\theta(\bx\mid\bz)\,p(\bz)\,\dd\bz.$$ $p_\theta(\bx\mid\bz)$가 Gaussian이어도 mean이 neural network $d_\theta(\bz)$이므로 이 적분은 closed form이 없다.
Prior에서 뽑은 sample로 Monte Carlo 근사를 하면 어떨까? $$p_\theta(\bx)\approx\frac1S\sum_{s=1}^Sp_\theta(\bx\mid\bz_s),\qquad\bz_s\sim p(\bz).$$ Unbiased이지만 실제로는 쓸 수 없다. 특정 $\bx$를 잘 설명하는 $\bz$는 prior 공간의 극히 작은 영역이고, prior에서 뽑은 대부분의 $\bz_s$는 $p_\theta(\bx\mid\bz_s)\approx0$을 준다. 추정량의 분산이 극도로 크다. 강의에서 "단순히 prior에서 하면 잘 안 된다"고 한 것이 이 문제이다. 필요한 것은 $\bx$를 evidence로 보고 그 $\bx$를 잘 만들 법한 $\bz$에 집중하는 sampling distribution, 이상적으로는 posterior $p_\theta(\bz\mid\bx)$이다. 그러나 posterior는 Bayes rule에 따라 $p_\theta(\bx\mid\bz)p(\bz)/p_\theta(\bx)$이고, 분모가 바로 계산할 수 없는 그 적분이다.
15.4Evidence lower bound
Posterior를 계산할 수 없으니 다루기 쉬운 family $q_\phi(\bz\mid\bx)$(예: Gaussian)로 근사한다. 이것이 variational inference이다.
임의의 $q_\phi(\bz\mid\bx)$에 대해 $$\log p_\theta(\bx)=\underbrace{\E_{q_\phi(\bz\mid\bx)}\big[\log p_\theta(\bx\mid\bz)\big]-\KL\big(q_\phi(\bz\mid\bx)\,\|\,p(\bz)\big)}_{\mathrm{ELBO}(\theta,\phi;\bx)}+\KL\big(q_\phi(\bz\mid\bx)\,\|\,p_\theta(\bz\mid\bx)\big).$$ 마지막 항이 0 이상이므로 $\log p_\theta(\bx)\ge\mathrm{ELBO}$이고, 등호는 $q_\phi(\bz\mid\bx)=p_\theta(\bz\mid\bx)$일 때 성립한다.
$\log p_\theta(\bx)$는 $\bz$와 무관하므로 $q$에 대한 expectation을 취해도 같다. $p_\theta(\bx)=p_\theta(\bx,\bz)/p_\theta(\bz\mid\bx)$를 넣고 $q$로 곱하고 나누면 $$\log p_\theta(\bx)=\E_q\Big[\log\frac{p_\theta(\bx,\bz)}{q(\bz\mid\bx)}\Big]+\E_q\Big[\log\frac{q(\bz\mid\bx)}{p_\theta(\bz\mid\bx)}\Big].$$ 둘째 항은 $\KL(q\|p_\theta(\bz\mid\bx))$이다. 첫째 항에 $p_\theta(\bx,\bz)=p_\theta(\bx\mid\bz)p(\bz)$를 넣으면 $\E_q[\log p_\theta(\bx\mid\bz)]-\KL(q\|p(\bz))$가 된다.
Jensen's inequality로도 같은 bound를 얻는다. $\log p_\theta(\bx)=\log\E_q\big[p_\theta(\bx,\bz)/q(\bz\mid\bx)\big]\ge\E_q\big[\log p_\theta(\bx,\bz)/q(\bz\mid\bx)\big]$. 위 정리는 그 차이(gap)가 정확히 posterior와의 KL임을 알려 준다.
Importance sampling 관점으로 보면 앞 절의 naive Monte Carlo와 연결된다. 임의의 proposal $q$에 대해 $$p_\theta(\bx)=\int\frac{p_\theta(\bx\mid\bz)p(\bz)}{q(\bz\mid\bx)}q(\bz\mid\bx)\,\dd\bz=\E_{\bz\sim q(\bz\mid\bx)}\Big[\frac{p_\theta(\bx,\bz)}{q(\bz\mid\bx)}\Big]$$ 이다. Prior를 proposal로 쓰는 것($q=p(\bz)$)이 naive Monte Carlo였고, 분산이 가장 작은 이상적인 proposal은 posterior $p_\theta(\bz\mid\bx)$이다(이때 weight $p_\theta(\bx,\bz)/q$가 상수 $p_\theta(\bx)$가 되어 분산이 0이다). ELBO는 이 importance-weighted 추정량의 log를 Jensen으로 bound한 것이고, $q$를 posterior에 가깝게 만들수록 bound가 tight해진다. Weight를 $K$개 평균한 뒤 log를 취하면 더 tight한 bound $\E\big[\log\frac1K\sum_k p_\theta(\bx,\bz_k)/q(\bz_k\mid\bx)\big]$를 얻으며, 이것이 IWAE(Burda et al., 2016)이다.
Decoder가 linear Gaussian인 경우 $p(\bz)=\N(\mathbf 0,\bI)$, $p(\bx\mid\bz)=\N(\bW\bz+\bmu,\sigma^2\bI)$(probabilistic PCA)에서는 marginal $p(\bx)=\N(\bmu,\bW\bW^\top+\sigma^2\bI)$와 posterior $$p(\bz\mid\bx)=\N\Big(\mathbf M^{-1}\bW^\top(\bx-\bmu),\ \sigma^2\mathbf M^{-1}\Big),\qquad\mathbf M=\bW^\top\bW+\sigma^2\bI$$ 가 모두 closed form이다. Gaussian family의 $q$가 posterior를 정확히 표현할 수 있으므로 ELBO가 log-likelihood와 같아진다. VAE는 decoder를 non-linear network로 바꾼 non-linear probabilistic PCA이며, 그 대가로 posterior가 intractable해진 것이다.
ELBO를 maximize하면 두 가지 일이 동시에 일어난다. $\phi$에 대해서는 $\log p_\theta(\bx)$가 $\phi$와 무관하므로 posterior와의 KL을 줄이는 것, 즉 더 좋은 posterior 근사를 찾는 것이다. $\theta$에 대해서는 log-likelihood의 lower bound를 올리는 것, 즉 근사적인 MLE이다. 원래 목표인 $\argmax_\theta\log p_\theta(\bx)$를 계산 가능한 $\argmax_{\theta,\phi}\mathrm{ELBO}$로 바꾼 것이다.
ELBO의 두 항은 각각 해석이 있다. 첫째 항 $\E_q[\log p_\theta(\bx\mid\bz)]$는 reconstruction 항으로, encoder가 준 $\bz$로 decoder가 $\bx$를 잘 복원해야 한다. 둘째 항 $\KL(q_\phi(\bz\mid\bx)\|p(\bz))$는 regularization 항으로, 각 $\bx$의 code distribution이 prior에서 너무 멀어지지 않게 한다. 이 두 번째 항 덕분에 prior 공간 전체가 decoder가 해석할 수 있는 영역이 되고, prior에서 sampling해 생성할 수 있게 된다.
15.5Amortized variational inference
전통적인 variational inference는 data point마다 별도의 variational parameter를 둔다. $q_i(\bz)=\N(\bmu_i,\diag(\boldsymbol\sigma_i^2))$로 두고 $(\bmu_i,\boldsymbol\sigma_i)$를 각각 최적화하는 식이다. 그러면 parameter 수가 $n$에 비례하고, 새 data가 오면 다시 최적화해야 한다.
Amortized inference는 $\bx$를 $(\bmu,\boldsymbol\sigma)$로 보내는 function 하나를 neural network로 학습한다. $$q_\phi(\bz\mid\bx)=\N\big(\bz;\,\bmu_\phi(\bx),\,\diag(\boldsymbol\sigma_\phi^2(\bx))\big).$$ Data마다의 최적화 비용을 network 학습에 "할부(amortize)"로 미리 지불하는 셈이다. 이 network가 VAE의 encoder이다. 결과적으로 구조가 autoencoder와 같아진다. Decoder(generator)를 학습시키기 위해 encoder가 존재한다고 보면 된다.
15.6Reparameterization trick
ELBO의 reconstruction 항을 $\phi$로 미분해야 한다. 그런데 $\nabla_\phi\E_{q_\phi(\bz\mid\bx)}[f(\bz)]$에서는 expectation을 취하는 distribution 자체가 $\phi$에 의존하므로 미분을 expectation 안으로 넣을 수 없다. Sample $\bz\sim q_\phi$를 뽑는 연산은 미분 가능하지 않다.
해결책은 randomness를 parameter와 분리하는 것이다. $\beps\sim\N(\mathbf 0,\bI)$를 먼저 뽑고 $$\bz=\bmu_\phi(\bx)+\boldsymbol\sigma_\phi(\bx)\odot\beps$$ 로 두면 $\bz$는 $q_\phi(\bz\mid\bx)$를 따르고, $\phi$에 대해 deterministic하고 미분 가능한 function이 된다. 그러면 $$\nabla_\phi\E_{q_\phi}[f(\bz)]=\E_{\beps\sim\N(0,\bI)}\big[\nabla_\phi f(\bmu_\phi(\bx)+\boldsymbol\sigma_\phi(\bx)\odot\beps)\big]$$ 이고, 이를 sample 하나로 Monte Carlo 근사해 일반적인 backpropagation으로 학습한다. 대안인 score function estimator $\E_q[f(\bz)\nabla_\phi\log q_\phi(\bz\mid\bx)]$(REINFORCE)도 unbiased이지만 분산이 훨씬 커서 VAE에서는 쓰지 않는다.
15.7VAE의 loss
Prior $\N(\mathbf 0,\bI)$과 diagonal Gaussian $q$ 사이의 KL은 closed form이다. Proposition 3.6에서 $\bmu_1=\bmu$, $\bSigma_1=\diag(\boldsymbol\sigma^2)$, $\bmu_2=\mathbf 0$, $\bSigma_2=\bI$로 두면 다음을 얻는다.
$$\KL\big(\N(\bmu,\diag(\boldsymbol\sigma^2))\,\|\,\N(\mathbf 0,\bI)\big)=\frac12\sum_{j=1}^{d_z}\big(\mu_j^2+\sigma_j^2-\log\sigma_j^2-1\big).$$
Decoder를 $p_\theta(\bx\mid\bz)=\N(\bx;d_\theta(\bz),\sigma_x^2\bI)$로 두면 reconstruction 항은 $-\frac{1}{2\sigma_x^2}\|\bx-d_\theta(\bz)\|^2+\text{const}$이고, pixel이 $[0,1]$인 binary에 가까운 data라면 Bernoulli decoder로 BCE를 쓴다. Sample 하나에 대한 최종 loss(negative ELBO)는 $$\L(\theta,\phi;\bx)=\frac{1}{2\sigma_x^2}\big\|\bx-d_\theta(\bmu_\phi(\bx)+\boldsymbol\sigma_\phi(\bx)\odot\beps)\big\|^2+\frac12\sum_j\big(\mu_j^2+\sigma_j^2-\log\sigma_j^2-1\big)$$ 이다. 구현에서는 수치 안정성을 위해 encoder가 $\log\sigma^2$를 출력하게 한다. $\sigma_x^2$는 두 항의 균형을 정하는 hyperparameter 역할을 하며, KL 항에 계수 $\beta$를 곱하는 $\beta$-VAE는 이를 명시적으로 조정해 더 disentangled된 latent를 얻으려는 변형이다.
생성은 간단하다. $\bz\sim\N(\mathbf 0,\bI)$을 뽑아 $d_\theta(\bz)$를 출력한다. VAE의 sample은 흐릿한 경향이 있는데, Gaussian likelihood가 여러 가능한 output의 평균을 내는 쪽으로 학습되기 때문이다. 이 한계가 GAN(Chapter 16)과 diffusion(Chapter 18)으로 이어진다.
구조는 같지만 목적이 반대다. AE의 목적은 encoder(압축)이고 decoder는 그것을 학습시키기 위한 도구이다. VAE의 목적은 decoder(생성)이고 encoder는 decoder가 잘 학습되도록 posterior를 근사하는 도구이다.
Chapter 16Generative Adversarial Network
Lecture Week 09 (GAN, cGAN, Style transfer, StyleGAN)
VAE는 likelihood의 lower bound를 maximize했다. Generative adversarial network(GAN)는 likelihood를 아예 계산하지 않는다. 대신 진짜와 가짜를 구분하는 판별자(discriminator)를 함께 학습시키고, 생성자(generator)는 그 판별자를 속이도록 학습된다. 이 장에서는 GAN의 minimax objective가 실제로 어떤 divergence를 최소화하는지 증명하고, 학습이 어려운 이유, conditional GAN, 그리고 style transfer와 StyleGAN으로 이어지는 흐름을 정리한다.
16.1Implicit generative model
Generator $G_\theta:\R^{d_z}\to\mathcal X$는 noise $\bz\sim p(\bz)$(보통 $\N(\mathbf 0,\bI)$ 또는 uniform)를 받아 sample $G_\theta(\bz)$를 출력하는 neural network이다. $G_\theta(\bz)$의 distribution을 $p_g$라 쓰면, $p_g$는 $p(\bz)$를 $G_\theta$로 옮긴 pushforward distribution이다.
이 model은 sampling은 쉽지만 density $p_g(\bx)$를 계산할 수 없다. $G_\theta$가 invertible하지 않고, $d_z$가 data 차원보다 작으면 $p_g$는 저차원 manifold 위에 놓여 Lebesgue density조차 없다. 이처럼 sampling 절차로만 정의되는 model을 implicit generative model이라 한다. Likelihood를 쓸 수 없으므로 MLE가 아닌 다른 학습 원리가 필요하다.
16.2Minimax objective
Discriminator $D_\psi:\mathcal X\to(0,1)$와 generator $G_\theta$에 대해 $$\min_G\max_D\;V(D,G)=\E_{\bx\sim p_{\text{data}}}\big[\log D(\bx)\big]+\E_{\bz\sim p(\bz)}\big[\log\big(1-D(G(\bz))\big)\big].$$
각 player의 입장에서 보면 다음과 같다.
- Discriminator: real $\bx$에 대해서는 $D(\bx)\to1$, generated $G(\bz)$에 대해서는 $D(G(\bz))\to0$이 되도록 $V$를 키운다. 이는 real에 label 1, fake에 label 0을 준 binary classification에서 BCE를 최소화하는 것과 정확히 같다. $\max_DV=-\min_D\text{BCE}$이다.
- Generator: $G(\bz)$가 $D$를 속여야 하므로 $D(G(\bz))\to1$이 되도록, 즉 $V$의 둘째 항을 줄이도록 학습된다. 첫째 항은 $G$와 무관하다.
강의에서 강조했듯 objective function과 loss function은 구분해야 한다. $V$는 $D$에게는 maximize할 objective이고 $G$에게는 minimize할 objective이다. 구현에서는 두 network 모두 minimize할 loss로 바꿔 쓰는데, 이때 부호와 형태가 바뀐다(아래 non-saturating loss).
16.3Optimal discriminator와 Jensen–Shannon divergence
$G$를 고정했을 때 최적의 $D$는 closed form으로 구할 수 있다. 이하에서 $p_{\text{data}}$와 $p_g$가 density를 가진다고 가정한다.
$G$가 고정되어 있으면 $V(D,G)$를 최대화하는 $D$는 $$D^\ast_G(\bx)=\frac{p_{\text{data}}(\bx)}{p_{\text{data}}(\bx)+p_g(\bx)}.$$
둘째 항을 $\bx=G(\bz)$로 바꿔 쓰면 $\E_{\bz}[\log(1-D(G(\bz)))]=\E_{\bx\sim p_g}[\log(1-D(\bx))]$이므로 $$V(D,G)=\int\Big[p_{\text{data}}(\bx)\log D(\bx)+p_g(\bx)\log\big(1-D(\bx)\big)\Big]\dd\bx.$$ 적분 안을 각 $\bx$마다 따로 최대화하면 된다. $a,b\ge0$, $(a,b)\ne(0,0)$일 때 $h(y)=a\log y+b\log(1-y)$는 $(0,1)$에서 strictly concave이고 $h'(y)=a/y-b/(1-y)=0$에서 $y=a/(a+b)$가 유일한 maximizer이다. $a=p_{\text{data}}(\bx)$, $b=p_g(\bx)$를 대입한다.
$D^\ast$는 "이 $\bx$가 real에서 왔을 posterior probability"이다(두 class의 prior가 1/2일 때). 즉 discriminator는 density ratio $p_{\text{data}}/p_g$를 추정하는 classifier이다. 이를 $V$에 대입하면 generator가 실제로 최소화하는 양이 드러난다.
$m=\frac12(p+q)$에 대해 $$\mathrm{JSD}(p\,\|\,q)=\frac12\KL(p\,\|\,m)+\frac12\KL(q\,\|\,m).$$ JSD는 symmetric이고 $0\le\mathrm{JSD}\le\log2$이며, $\mathrm{JSD}=0$은 $p=q$와 동치이다. $\sqrt{\mathrm{JSD}}$는 metric이다.
$C(G)=\max_DV(D,G)$라 하면 $$C(G)=-\log4+2\,\mathrm{JSD}(p_{\text{data}}\,\|\,p_g).$$ 따라서 $C(G)$의 global minimum은 $p_g=p_{\text{data}}$일 때, 그리고 그때만 달성되며 그 값은 $-\log4$이다. 이때 $D^\ast\equiv1/2$이다.
$D^\ast_G$를 대입하면 $$C(G)=\E_{p_{\text{data}}}\Big[\log\frac{p_{\text{data}}}{p_{\text{data}}+p_g}\Big]+\E_{p_g}\Big[\log\frac{p_g}{p_{\text{data}}+p_g}\Big].$$ 분모를 $2m$으로 쓰면 각 항은 $\E_{p_{\text{data}}}[\log(p_{\text{data}}/m)]-\log2=\KL(p_{\text{data}}\|m)-\log2$, $\E_{p_g}[\log(p_g/m)]-\log2=\KL(p_g\|m)-\log2$이다. 더하면 $-\log4+2\,\mathrm{JSD}$. JSD $\ge0$이고 등호가 $p_{\text{data}}=p_g$일 때뿐이므로 결론이 따른다.
정리하면, discriminator가 매 순간 최적이라면 GAN 학습은 $\mathrm{JSD}(p_{\text{data}}\|p_g)$를 최소화하는 것이다. MLE가 $\KL(p_{\text{data}}\|p_\theta)$를 최소화하는 것과 대비된다. Forward KL $\KL(p_{\text{data}}\|p_\theta)$는 data가 있는 곳에 model이 mass를 두지 않으면($p_\theta\to0$) 무한대의 penalty를 주지만, data가 없는 곳에 model이 mass를 두는 것은 상대적으로 약하게 벌준다. 그래서 MLE로 학습한 model은 모든 mode를 덮으려고 넓게 퍼지는(mode-covering) 경향이 있다. Reverse KL $\KL(p_\theta\|p_{\text{data}})$는 정반대로, data가 없는 곳의 mass를 강하게 벌주므로 일부 mode에 집중하는(mode-seeking) 경향이 있다. JSD는 symmetric하고 유계($\le\log2$)이며 두 성질의 중간쯤에 있다(Huszár, 2015). 실제 GAN이 mode-seeking으로 행동하는 데에는 divergence 자체보다 아래에서 볼 학습 dynamics의 영향이 더 크다. 어느 쪽이든 VAE sample이 흐리고 GAN sample이 선명한 경험적 차이를 이해하는 데 이 관점이 도움이 된다.
원 논문은 $G$와 $D$의 capacity가 충분하고 매 step $D$가 최적에 도달하며 $p_g$를 직접 update한다면 $p_g\to p_{\text{data}}$임도 보였다. $C(G)$가 $p_g$에 대해 convex이기 때문이다. 그러나 실제 학습은 $p_g$가 아니라 network parameter $\theta$ 공간에서 일어나고, 그 공간에서 objective는 convex가 아니므로 이 수렴 보장은 실제 학습에 그대로 적용되지 않는다.
16.4학습 알고리즘과 non-saturating loss
- 반복:
- $k$번 반복: real mini-batch $\{\bx_i\}_{i=1}^m$와 noise $\{\bz_i\}_{i=1}^m$를 뽑아 $D$를 $\nabla_\psi\frac1m\sum_i\big[\log D(\bx_i)+\log(1-D(G(\bz_i)))\big]$ 방향으로 update(ascent).
- Noise $\{\bz_i\}_{i=1}^m$를 뽑아 $G$를 update(아래 loss).
원 논문은 $k=1$을 썼고, 이후 대부분의 구현도 한 번씩 번갈아 update한다.
Minimax 식 그대로 $G$를 $\log(1-D(G(\bz)))$의 minimization으로 학습하면 초기에 문제가 생긴다. 학습 초기의 generated sample은 형편없어서 $D$가 쉽게 구분하고 $D(G(\bz))\approx0$이 된다. $D=\sigma(a)$($a$는 logit)라 하면 $$\frac{\partial}{\partial a}\log\big(1-\sigma(a)\big)=-\sigma(a)\approx0\quad(a\to-\infty)$$ 이므로 generator가 받는 gradient가 사라진다(saturation). 그래서 실제로는 generator loss를 $$\L_G=-\E_{\bz}\big[\log D(G(\bz))\big]$$ 로 바꾼다(non-saturating loss). $\frac{\partial}{\partial a}\log\sigma(a)=1-\sigma(a)\approx1$이므로 $D$가 확신할수록 오히려 강한 gradient를 받는다. "$D$를 속일 확률을 최대화"한다는 같은 목표를 표현하고 고정점($p_g=p_{\text{data}}$, $D\equiv1/2$)도 같지만, 학습 dynamics가 다르다. Generator 입장에서 이는 fake에 label 1을 붙인 BCE이다.
16.5학습이 어려운 이유
- Non-convergence와 불안정성: 두 network의 gradient descent–ascent는 일반적으로 equilibrium으로 수렴한다는 보장이 없고 진동할 수 있다. 간단한 bilinear game $\min_x\max_y xy$에서도 동시 gradient update는 원점 주위를 돌며 발산한다.
- Mode collapse: $G$가 $D$를 잘 속이는 소수의 sample만 계속 만드는 현상이다. 이론적인 목표는 $\min_G\max_D$인데 alternating update는 $\max_D\min_G$에 가까운 행동을 하기도 한다. 고정된 $D$에 대한 최적의 $G$는 $D$가 가장 "real"이라고 믿는 한 점으로 모든 $\bz$를 보내는 것이기 때문이다.
- Support mismatch: $p_{\text{data}}$와 $p_g$가 모두 저차원 manifold 위에 있으면 두 support가 거의 겹치지 않는다. 이때 완벽한 discriminator가 존재하고 $\mathrm{JSD}=\log2$로 상수가 되어 generator에게 유용한 gradient가 없다(Arjovsky & Bottou, 2017).
- 평가의 어려움: Likelihood가 없으므로 loss 값이 sample 품질을 반영하지 않는다. 별도의 metric(IS, FID; Chapter 18)이 필요하다.
마지막 두 문제에 대한 대표적인 대응이 Wasserstein GAN(Arjovsky et al., 2017)이다. JSD 대신 support가 겹치지 않아도 연속적으로 변하는 Wasserstein-1 distance를 쓴다. Kantorovich–Rubinstein duality에 의해 $$W_1(p_{\text{data}},p_g)=\sup_{\|f\|_L\le1}\E_{p_{\text{data}}}[f(\bx)]-\E_{p_g}[f(\bx)]$$ 이므로 discriminator(critic) $f$를 1-Lipschitz function class로 제한하고 이 차이를 최대화한다. Lipschitz 조건은 weight clipping이나 gradient penalty $\lambda\E[(\|\nabla_{\hat\bx}f(\hat\bx)\|-1)^2]$(WGAN-GP)로 근사한다. 이 밖에 spectral normalization, two time-scale learning rate 등 안정화 기법이 많이 제안되었다.
16.6Conditional GAN
원하는 종류의 sample을 생성하려면 조건 $\by$(class label, text, 다른 image 등)를 넣는다. Conditional GAN(Mirza & Osindero, 2014)은 generator와 discriminator 모두에 $\by$를 준다. $$\min_G\max_D\;\E_{(\bx,\by)\sim p_{\text{data}}}\big[\log D(\bx,\by)\big]+\E_{\bz,\by}\big[\log\big(1-D(G(\bz,\by),\by)\big)\big].$$ Discriminator가 "진짜 image인가"뿐 아니라 "조건과 맞는 image인가"까지 판단하므로, generator는 $p_{\text{data}}(\bx\mid\by)$를 배우게 된다. Label을 one-hot이나 embedding으로 $\bz$와 이어 붙이는 것이 가장 간단한 구현이다. 조건이 image인 경우(흑백→컬러, 지도→항공사진)가 pix2pix 계열의 image-to-image translation이다.
16.7Style transfer와 AdaIN
Style transfer는 content image의 구조는 유지하면서 style image의 질감과 색감을 입히는 문제이다. Gatys et al.(2016)은 pre-trained CNN(VGG)의 feature로 이를 정의했다. Feature map $\mathbf F^l\in\R^{C\times HW}$에 대해 content는 feature 자체로, style은 channel 간 상관을 나타내는 Gram matrix $\mathbf G^l=\mathbf F^l\mathbf F^{l\top}/(HW)$로 표현하고, 생성 image의 feature와 Gram matrix가 각각 content image, style image와 가까워지도록 image 자체를 최적화했다. Gram matrix는 공간 위치에 대한 평균이므로 "어디에"가 아니라 "어떤 pattern이 얼마나"의 통계, 즉 style을 담는다.
이후 연구들은 style이 feature map의 channel별 1차·2차 통계(mean, standard deviation)로 상당 부분 표현된다는 것을 발견했다. 이것이 Chapter 4에서 본 InstanceNorm이 style 정보를 제거하는 이유이기도 하다. Adaptive instance normalization(AdaIN; Huang & Belongie, 2017)은 content feature $\mathbf x$의 통계를 style feature $\mathbf y$의 통계로 바꿔 끼운다.
Channel $c$마다 공간 축 $(H,W)$에 대해 mean $\mu_c$, standard deviation $\sigma_c$를 계산하여 $$\mathrm{AdaIN}(\mathbf x,\mathbf y)_c=\sigma_c(\mathbf y)\,\frac{\mathbf x_c-\mu_c(\mathbf x)}{\sigma_c(\mathbf x)}+\mu_c(\mathbf y).$$
InstanceNorm에서 학습되는 affine parameter $(\gamma,\beta)$ 자리에 style image에서 계산한 $(\sigma(\mathbf y),\mu(\mathbf y))$를 넣은 것이다. 학습할 parameter가 없으므로, VGG encoder → AdaIN → 학습된 decoder 구조로 임의의 style을 feed-forward 한 번에 적용할 수 있다.
16.8StyleGAN
StyleGAN(Karras et al., 2019)은 AdaIN을 generator 설계에 가져왔다. 기존 generator는 $\bz$를 첫 layer의 input으로만 넣었다. StyleGAN은 다음과 같이 구성된다.
- Mapping network: 8-layer MLP $f:\mathcal Z\to\mathcal W$가 $\bz\sim\N(\mathbf 0,\bI)$를 intermediate latent $\mathbf w$로 보낸다. $\mathcal Z$는 Gaussian이라는 고정된 모양을 가져야 하지만 $\mathcal W$는 그런 제약이 없어, data의 변동 요인(포즈, 머리색 등)을 더 독립적인 축으로 펼칠(disentangle) 수 있다.
- Synthesis network: 학습된 constant $4\times4$ tensor에서 시작해 해상도를 키워 간다. 각 layer마다 학습된 affine 변환이 $\mathbf w$를 style $(\mathbf y_s,\mathbf y_b)$로 바꾸고, $\mathrm{AdaIN}(\mathbf x,\mathbf y)=\mathbf y_s\frac{\mathbf x-\mu(\mathbf x)}{\sigma(\mathbf x)}+\mathbf y_b$로 feature map의 통계를 정한다.
- Noise input: 각 layer의 feature map에 pixel별 random noise를 (channel별 학습된 scale로) 더해 머리카락 결, 주근깨 같은 확률적 세부를 만든다.
해상도가 낮은 layer의 style은 얼굴형이나 포즈 같은 큰 구조를, 높은 layer의 style은 색과 미세한 질감을 조절한다. 두 latent $\mathbf w_1,\mathbf w_2$를 layer별로 바꿔 넣는 style mixing으로 이를 확인할 수 있다. $\mathbf w$를 평균 $\bar{\mathbf w}$ 쪽으로 당기는 $\mathbf w'=\bar{\mathbf w}+\psi(\mathbf w-\bar{\mathbf w})$, $\psi\lt1$(truncation trick)은 다양성을 줄이는 대신 품질을 높인다.
GAN은 오랫동안 고해상도 image 생성의 최고 성능을 보였지만, 학습 불안정성과 mode collapse 때문에 다양성과 안정성 면에서 diffusion model(Chapter 18)에 자리를 내주었다. 다만 한 번의 forward pass로 생성한다는 속도 이점 때문에 diffusion을 몇 step으로 줄이는 distillation 연구에서 adversarial loss가 다시 쓰이고 있다.
Chapter 17Score-based Generative Model
Lecture Week 12, Week 13 (Score based)
Generative model의 목표는 $p_\theta(\bx)$를 배우는 것이다. 그런데 유연한 density model은 거의 언제나 계산할 수 없는 normalizing constant를 가진다. Score-based model은 density 대신 그 log의 gradient, 즉 score function을 배워 이 문제를 피한다. 이 장에서는 score matching의 유도(integration by parts), denoising score matching, Langevin dynamics를 이용한 sampling, 그리고 이를 여러 noise level로 확장한 NCSN을 다룬다. 다음 장의 diffusion model은 이 틀과 수학적으로 거의 같은 것이다.
참고 자료: Song & Ermon, "Generative Modeling by Estimating Gradients of the Data Distribution", NeurIPS 2019, 그리고 Yang Song의 blog post "Generative Modeling by Estimating Gradients of the Data Distribution"(2021).
17.1Normalizing constant 문제와 score function
임의의 neural network $E_\theta:\R^d\to\R$로 density를 정의하려면 $$p_\theta(\bx)=\frac{\exp(-E_\theta(\bx))}{Z_\theta},\qquad Z_\theta=\int\exp(-E_\theta(\bx))\,\dd\bx$$ 처럼 정규화해야 한다(energy-based model). 고차원에서 $Z_\theta$는 계산할 수 없고, MLE를 하려면 $\log Z_\theta$와 그 gradient가 필요하므로 학습이 어렵다. VAE는 latent variable과 bound로, GAN은 likelihood를 포기하는 것으로 이 문제를 피했다.
Density $p$의 score function은 input에 대한 log-density의 gradient이다. $$\mathbf s(\bx)=\nabla_\bx\log p(\bx)\in\R^d.$$
통계학에서 말하는 score $\nabla_\theta\log p_\theta(\bx)$는 parameter에 대한 gradient이지만, 여기서는 data $\bx$에 대한 gradient라는 점에 주의한다. 핵심 관찰은 $$\nabla_\bx\log p_\theta(\bx)=-\nabla_\bx E_\theta(\bx)-\underbrace{\nabla_\bx\log Z_\theta}_{=0}$$ 이다. $Z_\theta$는 $\bx$와 무관하므로 score에서 사라진다. Score function은 공간의 각 점에서 density가 가장 빨리 증가하는 방향을 가리키는 vector field로 생각할 수 있다. 이 vector field를 따라가면 data가 많은 곳으로 간다.
그렇다면 density 대신 score를 직접 network $\mathbf s_\theta:\R^d\to\R^d$로 근사하자. Score를 알면 다음 두 가지가 가능하다. (1) Score는 $\log p$를 additive constant를 제외하고 결정하므로(연결된 공간에서 gradient field의 potential은 상수 차이로 유일하다) distribution 정보를 모두 담고 있다. (2) Langevin dynamics로 score만 써서 sampling할 수 있다. 남은 문제는 진짜 score $\nabla_\bx\log p_{\text{data}}$를 모르는 상태에서 어떻게 $\mathbf s_\theta$를 학습하느냐이다.
17.2Score matching
자연스러운 objective는 model score와 data score의 차이의 제곱 평균이다(Fisher divergence). $$J(\theta)=\frac12\E_{p_{\text{data}}(\bx)}\Big[\big\|\mathbf s_\theta(\bx)-\nabla_\bx\log p_{\text{data}}(\bx)\big\|_2^2\Big].$$ $\nabla_\bx\log p_{\text{data}}$를 모르므로 그대로는 계산할 수 없다. 그러나 integration by parts로 이 항을 없앨 수 있다.
$p_{\text{data}}$와 $\mathbf s_\theta$가 미분 가능하고, $\E\|\mathbf s_\theta\|^2$, $\E\|\nabla\log p_{\text{data}}\|^2$가 유한하며, 각 $\theta$에 대해 $\|\bx\|\to\infty$일 때 $p_{\text{data}}(\bx)\,\mathbf s_\theta(\bx)\to\mathbf 0$이면 $$J(\theta)=\E_{p_{\text{data}}(\bx)}\Big[\tr\big(\nabla_\bx\mathbf s_\theta(\bx)\big)+\frac12\big\|\mathbf s_\theta(\bx)\big\|_2^2\Big]+C,$$ 여기서 $C$는 $\theta$와 무관한 상수이고 $\nabla_\bx\mathbf s_\theta$는 $\mathbf s_\theta$의 Jacobian이다.
먼저 1차원에서 보인다. $p=p_{\text{data}}$, $s=s_\theta$로 쓰고 제곱을 전개하면 $$J(\theta)=\frac12\E[s(x)^2]-\E\big[s(x)\,(\log p)'(x)\big]+\frac12\E\big[((\log p)'(x))^2\big].$$ 마지막 항은 $\theta$와 무관하다. 가운데 항은 $(\log p)'=p'/p$이므로 $$\E\big[s\,(\log p)'\big]=\int p(x)s(x)\frac{p'(x)}{p(x)}\dd x=\int s(x)p'(x)\,\dd x=\Big[s(x)p(x)\Big]_{-\infty}^{\infty}-\int s'(x)p(x)\,\dd x=-\E[s'(x)].$$ 경계항은 가정에 의해 0이다. 따라서 $J(\theta)=\E[\frac12s^2+s']+C$. $d$차원에서는 $\|\mathbf s-\nabla\log p\|^2=\sum_{i=1}^d(s_i-\partial_i\log p)^2$의 각 성분에 대해 $x_i$ 방향으로 같은 계산을 하면 cross term이 $-\E[\partial_is_i]$가 되고, 합하면 $-\E[\tr(\nabla_\bx\mathbf s_\theta)]$이다.
결과 식에는 $p_{\text{data}}$가 expectation을 취하는 데에만 나타나므로 sample 평균으로 근사할 수 있다. $$J(\theta)\approx\frac1n\sum_{i=1}^n\Big[\tr\big(\nabla_\bx\mathbf s_\theta(\bx_i)\big)+\frac12\big\|\mathbf s_\theta(\bx_i)\big\|^2\Big]+C.$$ 이 식을 minimize한다는 것의 의미를 보자. $\frac12\|\mathbf s_\theta\|^2$은 data 점에서 score가 0이기를, $\tr(\nabla_\bx\mathbf s_\theta)$는 그 점에서 Jacobian의 trace가 음수이기를 요구한다. $\mathbf s_\theta=\nabla\log p_\theta$라면 이 Jacobian은 $\log p_\theta$의 Hessian이므로, 두 조건은 data 점이 $\log p_\theta$의 local maximum 근처에 있기를 요구하는 것이다.
Jacobian trace의 비용
$\tr(\nabla_\bx\mathbf s_\theta(\bx))=\sum_i\partial s_{\theta,i}/\partial x_i$를 정확히 계산하려면 대각 성분마다 backward pass가 필요하므로 $d$번의 backpropagation이 든다. $d$가 수만인 image에서는 비현실적이다. Random projection $\mathbf v$로 $\E_\mathbf v[\mathbf v^\top\nabla_\bx\mathbf s_\theta\mathbf v]$를 쓰는 sliced score matching(Song et al., 2019)도 있지만, 가장 널리 쓰이는 해결책은 다음의 denoising score matching이다.
17.3Denoising score matching
Data에 알려진 noise를 더한 distribution의 score를 배우면 Jacobian 계산이 필요 없어진다. Noise kernel $q_\sigma(\tilde\bx\mid\bx)$로 perturbed distribution $$q_\sigma(\tilde\bx)=\int q_\sigma(\tilde\bx\mid\bx)\,p_{\text{data}}(\bx)\,\dd\bx$$ 를 정의한다.
다음 두 objective는 $\theta$와 무관한 상수만큼만 다르다. $$\frac12\E_{q_\sigma(\tilde\bx)}\Big[\big\|\mathbf s_\theta(\tilde\bx)-\nabla_{\tilde\bx}\log q_\sigma(\tilde\bx)\big\|^2\Big]\quad\text{and}\quad\frac12\E_{p_{\text{data}}(\bx)\,q_\sigma(\tilde\bx\mid\bx)}\Big[\big\|\mathbf s_\theta(\tilde\bx)-\nabla_{\tilde\bx}\log q_\sigma(\tilde\bx\mid\bx)\big\|^2\Big].$$
두 식을 전개하면 $\frac12\E\|\mathbf s_\theta(\tilde\bx)\|^2$ 항은 $\tilde\bx$의 marginal이 둘 다 $q_\sigma(\tilde\bx)$이므로 같다. $\|\nabla\log\cdot\|^2$ 항은 $\theta$와 무관하다. Cross term만 비교하면 된다. 첫 번째 식의 cross term은 $$\E_{q_\sigma(\tilde\bx)}\big[\mathbf s_\theta(\tilde\bx)^\top\nabla_{\tilde\bx}\log q_\sigma(\tilde\bx)\big]=\int\mathbf s_\theta(\tilde\bx)^\top\nabla_{\tilde\bx}q_\sigma(\tilde\bx)\,\dd\tilde\bx=\int\mathbf s_\theta(\tilde\bx)^\top\!\int p_{\text{data}}(\bx)\nabla_{\tilde\bx}q_\sigma(\tilde\bx\mid\bx)\,\dd\bx\,\dd\tilde\bx.$$ $\nabla_{\tilde\bx}q_\sigma(\tilde\bx\mid\bx)=q_\sigma(\tilde\bx\mid\bx)\nabla_{\tilde\bx}\log q_\sigma(\tilde\bx\mid\bx)$를 쓰면 이는 $\E_{p_{\text{data}}(\bx)q_\sigma(\tilde\bx\mid\bx)}\big[\mathbf s_\theta(\tilde\bx)^\top\nabla_{\tilde\bx}\log q_\sigma(\tilde\bx\mid\bx)\big]$로 두 번째 식의 cross term과 같다. (적분 순서 교환과 미분·적분 교환에 필요한 regularity를 가정한다.)
두 번째 식의 target $\nabla_{\tilde\bx}\log q_\sigma(\tilde\bx\mid\bx)$는 우리가 정한 noise model의 score이므로 closed form이다. Gaussian kernel $q_\sigma(\tilde\bx\mid\bx)=\N(\tilde\bx;\bx,\sigma^2\bI)$이면 $\log q_\sigma(\tilde\bx\mid\bx)=-\frac{\|\tilde\bx-\bx\|^2}{2\sigma^2}+\text{const}$이므로 $$\nabla_{\tilde\bx}\log q_\sigma(\tilde\bx\mid\bx)=-\frac{\tilde\bx-\bx}{\sigma^2}.$$ (강의 슬라이드에는 분자에 제곱이 붙어 있었는데, gradient는 vector이므로 제곱이 없는 위 식이 맞다.) 따라서 학습 objective는 $$\ell(\theta;\sigma)=\frac12\E_{\bx\sim p_{\text{data}}}\E_{\tilde\bx\sim\N(\bx,\sigma^2\bI)}\Big[\Big\|\mathbf s_\theta(\tilde\bx)+\frac{\tilde\bx-\bx}{\sigma^2}\Big\|^2\Big].$$ $\tilde\bx=\bx+\sigma\beps$, $\beps\sim\N(\mathbf 0,\bI)$로 쓰면 target은 $-\beps/\sigma$이다.
직관은 이렇다. Data $\bx$에 Gaussian noise를 더해 $\tilde\bx$를 만들고, $\tilde\bx$에서 원래 $\bx$로 돌아가는 방향(noise의 반대 방향)을 예측하게 한다. 즉 score network는 "$\bx$에 어떤 noise가 더해졌는가"를 배우는 denoiser이다. 여기까지가 training이다. 이 연결은 다음 식으로 정확해진다.
$\tilde\bx=\bx+\sigma\beps$, $\beps\sim\N(\mathbf 0,\bI)$이면 $$\E[\bx\mid\tilde\bx]=\tilde\bx+\sigma^2\nabla_{\tilde\bx}\log q_\sigma(\tilde\bx).$$
$\nabla_{\tilde\bx}q_\sigma(\tilde\bx)=\int p(\bx)\nabla_{\tilde\bx}\N(\tilde\bx;\bx,\sigma^2\bI)\,\dd\bx=\int p(\bx)\N(\tilde\bx;\bx,\sigma^2\bI)\frac{\bx-\tilde\bx}{\sigma^2}\dd\bx$. 양변을 $q_\sigma(\tilde\bx)$로 나누면 $\nabla\log q_\sigma(\tilde\bx)=\frac{1}{\sigma^2}\big(\E[\bx\mid\tilde\bx]-\tilde\bx\big)$.
최적의 score network는 posterior mean denoiser와 동치이다. 한 가지 대가는, denoising score matching이 배우는 것은 $p_{\text{data}}$가 아니라 noise가 섞인 $q_\sigma$의 score라는 점이다. $\sigma$가 작을수록 $q_\sigma\approx p_{\text{data}}$이지만, 아래에서 보듯 작은 $\sigma$ 하나만으로는 다른 문제가 생긴다.
17.4Langevin dynamics로 sampling하기
학습으로 vector field를 얻었다. 실제로 원하는 것은 data distribution에서의 sample이다. Data를 무작위로 뿌려 놓고 vector를 따라가면 되는데, 그냥 따라가기만 하면(gradient ascent) 모든 점이 $\log p$의 mode로 모여 버린다. Noise를 함께 넣어야 distribution 전체를 탐색한다.
Step size $\epsilon>0$, 초기값 $\tilde\bx_0\sim\pi_0$에 대해 $$\tilde\bx_{t+1}=\tilde\bx_t+\frac\epsilon2\nabla_\bx\log p(\tilde\bx_t)+\sqrt\epsilon\,\bz_t,\qquad\bz_t\sim\N(\mathbf 0,\bI).$$
이는 stochastic differential equation $\dd\bx_t=\frac12\nabla\log p(\bx_t)\dd t+\dd\mathbf B_t$($\mathbf B_t$는 Brownian motion)의 Euler–Maruyama discretization이고, 이 SDE의 stationary distribution이 $p$이다. Regularity 조건 하에서 $\epsilon\to0$, $T\to\infty$이면 $\tilde\bx_T$의 distribution은 $p$로 수렴한다. $\epsilon>0$이면 discretization error가 있으며, 정확히 하려면 Metropolis–Hastings correction을 붙이지만(MALA) 실제로는 생략한다. 여기서 $\nabla\log p$ 자리에 학습된 $\mathbf s_\theta$를 넣으면 score만으로 sampling할 수 있다. 강의 슬라이드의 update 식 $\tilde\bx_{i+1}\leftarrow\tilde\bx_i+\frac\epsilon2\mathbf s_\theta(\tilde\bx_i)$에는 noise 항 $\sqrt\epsilon\,\bz_t$가 빠져 있었는데, 바로 그 항이 없으면 mode로 수렴만 하고 distribution을 재현하지 못한다.
17.5Naive 접근의 세 가지 문제
1. Manifold hypothesis
실제 data는 고차원 공간에 고르게 퍼져 있지 않고 저차원 manifold 근처에 몰려 있다. Pixel을 random하게 생성하면 noise일 뿐이다. 그러면 (a) manifold 밖에서는 $p_{\text{data}}=0$이라 $\nabla_\bx\log p_{\text{data}}$가 정의되지 않고, (b) score matching의 consistency는 data distribution이 전체 공간에 support를 가질 때 성립하므로 이론적 보장이 깨진다. 또 data는 유한 개의 이산적인 점이다.
2. 저밀도 영역에서의 부정확한 score
Objective는 $\E_{p_{\text{data}}}[\cdot]$로 가중되므로, data가 거의 없는 영역의 score 오차는 loss에 거의 반영되지 않는다. 애초에 data가 없는 곳은 학습이 안 된다. 그런데 Langevin dynamics는 random한 초기값, 대부분 저밀도 영역에서 출발하므로 처음부터 부정확한 vector field를 따라가게 된다.
3. Mixture weight를 잃어버림
$p_{\text{data}}=\pi p_1+(1-\pi)p_2$이고 $p_1,p_2$의 support가 disjoint라 하자. $p_1$의 support 위에서는 $\log p_{\text{data}}=\log\pi+\log p_1$이므로 $$\nabla_\bx\log p_{\text{data}}(\bx)=\nabla_\bx\log p_1(\bx).$$ $\log\pi$는 상수라 gradient에서 사라진다. Score는 두 mode의 상대적 비중 $\pi$에 대한 정보를 담지 않는다. Support가 근사적으로만 분리되어 있어도, 두 mode 사이의 저밀도 영역을 건너기 어려워 Langevin dynamics가 현실적인 시간 안에 올바른 비율로 섞이지 못한다(slow mixing). 결과적으로 sample에서 두 mode의 비율이 틀어진다.
17.6Noise Conditional Score Network
세 문제 모두 data에 noise를 더하는 것으로 완화된다.
- Gaussian noise를 더한 distribution은 전체 공간에 support를 가지므로 score가 어디서나 잘 정의되고, manifold에 갇히지 않는다.
- 큰 noise는 저밀도 영역까지 sample을 퍼뜨려 그곳에 학습 신호를 준다.
- Noise가 큰 distribution에서는 mode 사이가 연결되어 mixing이 쉽다.
그러나 noise가 크면 원래 distribution에서 멀어진다. 그래서 여러 noise level을 함께 쓴다. 큰 noise에서 시작해 점점 줄이면서 원래 distribution으로 수렴하는 일련의 distribution을 따라간다.
$\sigma_1/\sigma_2=\cdots=\sigma_{L-1}/\sigma_L>1$인 geometric sequence $\{\sigma_i\}_{i=1}^L$($\sigma_1$은 data 점 사이 최대 거리 수준으로 크게, $\sigma_L$은 충분히 작게)에 대해 perturbed distribution $q_{\sigma}(\bx)=\int p_{\text{data}}(\mathbf t)\N(\bx;\mathbf t,\sigma^2\bI)\,\dd\mathbf t$을 정의한다. 하나의 network $\mathbf s_\theta(\bx,\sigma)$가 모든 level에서 $$\mathbf s_\theta(\bx,\sigma_i)\approx\nabla_\bx\log q_{\sigma_i}(\bx),\qquad i=1,\dots,L$$ 가 되도록 다음을 minimize한다. $$\L\big(\theta;\{\sigma_i\}\big)=\frac1L\sum_{i=1}^L\lambda(\sigma_i)\,\ell(\theta;\sigma_i),\qquad\ell(\theta;\sigma)=\frac12\E_{p_{\text{data}}(\bx)}\E_{\tilde\bx\sim\N(\bx,\sigma^2\bI)}\Big[\Big\|\mathbf s_\theta(\tilde\bx,\sigma)+\frac{\tilde\bx-\bx}{\sigma^2}\Big\|^2\Big].$$
$\bx$와 $\sigma$를 함께 입력으로 받는 network 하나로 모든 noise level을 jointly 학습한다는 것이 이름(noise conditional)의 의미이다. Weight는 $\lambda(\sigma)=\sigma^2$로 둔다. 최적 score의 크기가 대략 $\|\nabla\log q_\sigma\|\propto1/\sigma$이므로, $\sigma^2$를 곱하면 모든 level의 loss가 같은 scale이 된다. 실제로 $\tilde\bx=\bx+\sigma\beps$를 대입하면 $$\sigma^2\ell(\theta;\sigma)=\frac12\E\big[\|\sigma\,\mathbf s_\theta(\bx+\sigma\beps,\sigma)+\beps\|^2\big]$$ 로 $\sigma$에 의존하지 않는 크기의 noise 예측 문제가 된다. 이 형태는 다음 장 DDPM의 loss와 사실상 같다.
- $\tilde\bx_0$를 uniform 등 단순한 distribution에서 초기화. Step size 상수 $\epsilon$, level당 step 수 $T$.
- For $i=1,\dots,L$ (큰 noise부터):
- $\alpha_i=\epsilon\cdot\sigma_i^2/\sigma_L^2$
- For $t=1,\dots,T$: $\bz_t\sim\N(\mathbf 0,\bI)$, $\tilde\bx_t=\tilde\bx_{t-1}+\frac{\alpha_i}{2}\mathbf s_\theta(\tilde\bx_{t-1},\sigma_i)+\sqrt{\alpha_i}\,\bz_t$
- $\tilde\bx_0\leftarrow\tilde\bx_T$
- Return $\tilde\bx_T$.
Step size를 $\sigma_i^2$에 비례하게 두는 이유는 "signal-to-noise ratio" $\frac{\alpha_i\mathbf s_\theta}{2\sqrt{\alpha_i}\bz}$의 크기를 level에 무관하게 유지하기 위해서이다. 큰 noise 단계에서 대략적인 위치와 mode 간 비율을 잡고, 작은 noise 단계에서 세부를 다듬는다. 복잡한 것을 한 번에 하면 커버하기 어려우니 단계적으로 하자는 것이다. 앞의 mixture 예에서 single-level Langevin은 두 mode의 비율을 틀리게 복원하지만, annealed Langevin은 올바른 비율로 복원한다.
세 문제(manifold, 저밀도 영역, mixing)는 각각 training에서 noise를 더하는 것, 여러 noise level을 조건으로 하는 하나의 network(NCSN), sampling에서 annealed Langevin dynamics로 해결된다. 이후 Song et al.(2021)은 noise level을 연속 시간 $t$로 보내 이 과정을 SDE로 통합했고(Chapter 20), 그 특수한 경우가 다음 장의 DDPM이다.
Chapter 18Diffusion Model
Lecture Week 12 (Metrics), Week 13 (DDPM, DDIM, Guided, Stable Diffusion)
Diffusion model은 data에 noise를 조금씩 더해 완전한 Gaussian noise로 만드는 과정을 정의하고, 그 역과정을 neural network로 학습한다. VAE처럼 ELBO로 학습하지만 encoder가 고정되어 있고, score-based model처럼 noise를 예측하지만 이산적인 Markov chain으로 정식화된다. 이 장에서는 DDPM의 forward·reverse process와 loss를 처음부터 유도하고, 빠른 sampling을 위한 DDIM, 조건부 생성을 위한 guidance, 그리고 latent diffusion(Stable Diffusion)을 다룬다. 마지막으로 생성 model의 평가 지표를 정리한다.
18.1VAE에서 diffusion으로
VAE를 다시 보자. $\bx$를 encoder로 noise 같은 $\bz$로 보내고, decoder로 다시 $\bx$를 만든다. 이 한 번의 변환을 여러 단계로 쪼개면 어떨까? $\bx_0$(data)에서 시작해 $\bx_1,\bx_2,\dots,\bx_T$로 갈수록 noise가 늘어나 마지막에는 완벽한 noise가 되고, 각 단계를 거꾸로 되돌리는 작은 decoder를 학습한다. 각 단계의 변화가 작으므로 역방향 한 단계는 단순한 Gaussian으로 근사할 수 있다. 다른 점은 encoder 쪽(forward process)이 학습되지 않는 고정된 noise 과정이라는 것이다.
이하 notation: $\beta_t\in(0,1)$은 noise schedule, $\alpha_t=1-\beta_t$, $\bar\alpha_t=\prod_{s=1}^t\alpha_s$이다. DDPM의 기본 설정은 $T=1000$, $\beta_t$를 $10^{-4}$에서 $0.02$까지 linear하게 증가시키는 것이다.
18.2Forward process
$$q(\bx_{1:T}\mid\bx_0)=\prod_{t=1}^Tq(\bx_t\mid\bx_{t-1}),\qquad q(\bx_t\mid\bx_{t-1})=\N\big(\bx_t;\sqrt{\alpha_t}\,\bx_{t-1},\,\beta_t\bI\big).$$ 즉 $\bx_t=\sqrt{\alpha_t}\,\bx_{t-1}+\sqrt{\beta_t}\,\beps_t$, $\beps_t\iid\N(\mathbf 0,\bI)$.
단순히 noise를 더하지 않고 $\sqrt{\alpha_t}$로 줄인 뒤 더하는 이유는 분산을 유지하기 위해서이다. $\Var(\bx_{t-1})=\bI$이면 $\Var(\bx_t)=\alpha_t\bI+\beta_t\bI=\bI$이다(variance preserving). 중요한 성질은 임의의 $t$로 한 번에 갈 수 있다는 것이다.
$$q(\bx_t\mid\bx_0)=\N\big(\bx_t;\sqrt{\bar\alpha_t}\,\bx_0,\,(1-\bar\alpha_t)\bI\big),\quad\text{즉}\quad\bx_t=\sqrt{\bar\alpha_t}\,\bx_0+\sqrt{1-\bar\alpha_t}\,\beps,\ \ \beps\sim\N(\mathbf 0,\bI).$$
$t$에 대한 귀납법. $t=1$이면 정의 그대로이다($\bar\alpha_1=\alpha_1$). $\bx_{t-1}=\sqrt{\bar\alpha_{t-1}}\bx_0+\sqrt{1-\bar\alpha_{t-1}}\,\beps'$라 하면 $$\bx_t=\sqrt{\alpha_t}\bx_{t-1}+\sqrt{1-\alpha_t}\,\beps_t=\sqrt{\bar\alpha_t}\bx_0+\underbrace{\sqrt{\alpha_t(1-\bar\alpha_{t-1})}\,\beps'+\sqrt{1-\alpha_t}\,\beps_t}_{\text{independent Gaussians의 합}}.$$ 두 noise 항의 합은 mean 0, covariance $\big(\alpha_t-\alpha_t\bar\alpha_{t-1}+1-\alpha_t\big)\bI=(1-\bar\alpha_t)\bI$인 Gaussian이다.
$\bar\alpha_T\approx0$이 되도록 schedule을 잡으면($T=1000$, 위 schedule에서 $\bar\alpha_T\approx4\times10^{-5}$) $q(\bx_T\mid\bx_0)\approx\N(\mathbf 0,\bI)$로 $\bx_0$와 거의 무관해진다. 그리고 training에서는 chain을 따라갈 필요 없이 $t$를 random하게 뽑아 $\bx_t$를 위 식으로 바로 만들 수 있다.
Forward process의 역방향 조건부 분포는 일반적으로 계산할 수 없지만, $\bx_0$를 함께 조건으로 주면 closed form이 된다.
$t\ge2$에 대해 $q(\bx_{t-1}\mid\bx_t,\bx_0)=\N\big(\bx_{t-1};\tilde\bmu_t(\bx_t,\bx_0),\tilde\beta_t\bI\big)$이고 $$\tilde\bmu_t(\bx_t,\bx_0)=\frac{\sqrt{\bar\alpha_{t-1}}\,\beta_t}{1-\bar\alpha_t}\bx_0+\frac{\sqrt{\alpha_t}\,(1-\bar\alpha_{t-1})}{1-\bar\alpha_t}\bx_t,\qquad\tilde\beta_t=\frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}\beta_t.$$
Markov 성질로 $q(\bx_t\mid\bx_{t-1},\bx_0)=q(\bx_t\mid\bx_{t-1})$이므로 Bayes rule에서 $$q(\bx_{t-1}\mid\bx_t,\bx_0)\propto q(\bx_t\mid\bx_{t-1})\,q(\bx_{t-1}\mid\bx_0)\propto\exp\Big\{-\frac12\Big[\frac{\|\bx_t-\sqrt{\alpha_t}\bx_{t-1}\|^2}{\beta_t}+\frac{\|\bx_{t-1}-\sqrt{\bar\alpha_{t-1}}\bx_0\|^2}{1-\bar\alpha_{t-1}}\Big]\Big\}.$$ $\bx_{t-1}$에 대한 quadratic form이므로 Gaussian이다. 이차항의 계수(precision)는 $$\frac{\alpha_t}{\beta_t}+\frac{1}{1-\bar\alpha_{t-1}}=\frac{\alpha_t(1-\bar\alpha_{t-1})+\beta_t}{\beta_t(1-\bar\alpha_{t-1})}=\frac{1-\bar\alpha_t}{\beta_t(1-\bar\alpha_{t-1})}$$ 이고(분자에서 $\alpha_t+\beta_t=1$, $\alpha_t\bar\alpha_{t-1}=\bar\alpha_t$), 그 역수가 $\tilde\beta_t$이다. 일차항의 계수는 $\frac{\sqrt{\alpha_t}}{\beta_t}\bx_t+\frac{\sqrt{\bar\alpha_{t-1}}}{1-\bar\alpha_{t-1}}\bx_0$이고 여기에 $\tilde\beta_t$를 곱하면 $\tilde\bmu_t$가 된다.
18.3Reverse process와 ELBO
$$p_\theta(\bx_{0:T})=p(\bx_T)\prod_{t=1}^Tp_\theta(\bx_{t-1}\mid\bx_t),\qquad p(\bx_T)=\N(\mathbf 0,\bI),\qquad p_\theta(\bx_{t-1}\mid\bx_t)=\N\big(\bx_{t-1};\bmu_\theta(\bx_t,t),\sigma_t^2\bI\big).$$ Variance $\sigma_t^2$는 학습하지 않고 $\beta_t$ 또는 $\tilde\beta_t$로 고정한다.
Generative model은 $p_\theta(\bx_0)=\int p_\theta(\bx_{0:T})\,\dd\bx_{1:T}$이고, $\bx_{1:T}$는 latent variable이다. VAE와 똑같이 이 적분은 계산할 수 없으므로 ELBO를 쓴다. 차이는 variational distribution이 학습되는 encoder가 아니라 고정된 forward process $q(\bx_{1:T}\mid\bx_0)$라는 것이다.
$$-\log p_\theta(\bx_0)\le\E_q\Big[-\log\frac{p_\theta(\bx_{0:T})}{q(\bx_{1:T}\mid\bx_0)}\Big]=\underbrace{\KL\big(q(\bx_T\mid\bx_0)\|p(\bx_T)\big)}_{L_T}+\sum_{t=2}^T\underbrace{\E_q\Big[\KL\big(q(\bx_{t-1}\mid\bx_t,\bx_0)\,\|\,p_\theta(\bx_{t-1}\mid\bx_t)\big)\Big]}_{L_{t-1}}\underbrace{-\,\E_q\big[\log p_\theta(\bx_0\mid\bx_1)\big]}_{L_0}.$$
부등식은 Theorem 15.1와 같은 Jensen 논증이다. 분해를 보이기 위해 $t\ge2$에서 Markov 성질과 Bayes rule로 $$q(\bx_t\mid\bx_{t-1})=q(\bx_t\mid\bx_{t-1},\bx_0)=\frac{q(\bx_{t-1}\mid\bx_t,\bx_0)\,q(\bx_t\mid\bx_0)}{q(\bx_{t-1}\mid\bx_0)}$$ 로 쓴다. 그러면 $$q(\bx_{1:T}\mid\bx_0)=q(\bx_1\mid\bx_0)\prod_{t=2}^T\frac{q(\bx_{t-1}\mid\bx_t,\bx_0)\,q(\bx_t\mid\bx_0)}{q(\bx_{t-1}\mid\bx_0)}=q(\bx_T\mid\bx_0)\prod_{t=2}^Tq(\bx_{t-1}\mid\bx_t,\bx_0)$$ 이다(분수 부분이 telescoping되어 $q(\bx_T\mid\bx_0)/q(\bx_1\mid\bx_0)$만 남는다). 따라서 $$-\log\frac{p_\theta(\bx_{0:T})}{q(\bx_{1:T}\mid\bx_0)}=-\log\frac{p(\bx_T)}{q(\bx_T\mid\bx_0)}-\sum_{t=2}^T\log\frac{p_\theta(\bx_{t-1}\mid\bx_t)}{q(\bx_{t-1}\mid\bx_t,\bx_0)}-\log p_\theta(\bx_0\mid\bx_1).$$ 각 항의 $q$-expectation을 취하면 첫 항은 $L_T$, 가운데 항들은 $\bx_t$에 대한 바깥 expectation 안의 KL, 마지막 항은 $L_0$가 된다.
$L_T$는 learnable parameter가 없는 상수이다. $L_0$는 마지막 discrete decoder 항으로 실제로는 비중이 작다. 핵심은 $L_{t-1}$이며, 두 Gaussian 사이의 KL이므로 closed form이다. 두 distribution의 covariance가 같은 $\sigma_t^2\bI$라 놓으면(정확히는 $\tilde\beta_t$와 $\sigma_t^2$의 차이에서 오는 상수가 붙는다) $$L_{t-1}=\E_q\Big[\frac{1}{2\sigma_t^2}\big\|\tilde\bmu_t(\bx_t,\bx_0)-\bmu_\theta(\bx_t,t)\big\|^2\Big]+C.$$ 즉 network가 할 일은 "noisy한 $\bx_t$를 보고, $\bx_0$를 알았다면 계산했을 posterior mean $\tilde\bmu_t$를 예측하는 것"이다.
18.4ε-prediction과 simplified loss
$\bx_t=\sqrt{\bar\alpha_t}\bx_0+\sqrt{1-\bar\alpha_t}\beps$에서 $\bx_0=\frac{1}{\sqrt{\bar\alpha_t}}\big(\bx_t-\sqrt{1-\bar\alpha_t}\,\beps\big)$를 $\tilde\bmu_t$에 대입하면 $$\tilde\bmu_t=\frac{1}{\sqrt{\alpha_t}}\Big(\bx_t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\beps\Big).$$ (검산: $\bx_t$의 계수는 $\frac{\sqrt{\bar\alpha_{t-1}}\beta_t}{(1-\bar\alpha_t)\sqrt{\bar\alpha_t}}+\frac{\sqrt{\alpha_t}(1-\bar\alpha_{t-1})}{1-\bar\alpha_t}=\frac{\beta_t+\alpha_t-\bar\alpha_t}{\sqrt{\alpha_t}(1-\bar\alpha_t)}=\frac{1}{\sqrt{\alpha_t}}$이고, $\beps$의 계수는 $-\frac{\sqrt{\bar\alpha_{t-1}}\beta_t}{1-\bar\alpha_t}\cdot\frac{\sqrt{1-\bar\alpha_t}}{\sqrt{\bar\alpha_t}}=-\frac{\beta_t}{\sqrt{\alpha_t}\sqrt{1-\bar\alpha_t}}$.)
$\bx_t$는 network input으로 주어지므로, 모르는 것은 $\beps$뿐이다. 그래서 $\bmu_\theta$를 같은 형태로 parameterize하고 network $\beps_\theta(\bx_t,t)$가 noise를 예측하게 한다. $$\bmu_\theta(\bx_t,t)=\frac{1}{\sqrt{\alpha_t}}\Big(\bx_t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\beps_\theta(\bx_t,t)\Big).$$ 대입하면 $$L_{t-1}=\E_{\bx_0,\beps}\Big[\frac{\beta_t^2}{2\sigma_t^2\alpha_t(1-\bar\alpha_t)}\Big\|\beps-\beps_\theta\big(\sqrt{\bar\alpha_t}\bx_0+\sqrt{1-\bar\alpha_t}\,\beps,\ t\big)\Big\|^2\Big]+C.$$ Ho et al.은 앞의 가중치를 버리고 $t$를 uniform하게 뽑는 단순한 loss가 sample 품질이 더 좋음을 발견했다. $$\L_{\text{simple}}(\theta)=\E_{t\sim\mathcal U\{1,\dots,T\},\,\bx_0\sim q,\,\beps\sim\N(\mathbf 0,\bI)}\Big[\big\|\beps-\beps_\theta\big(\sqrt{\bar\alpha_t}\bx_0+\sqrt{1-\bar\alpha_t}\,\beps,\ t\big)\big\|^2\Big].$$ 가중치를 버리면 작은 $t$(noise가 적은 쉬운 단계)의 비중이 줄고 큰 $t$의 어려운 denoising에 집중하게 된다.
- repeat
- $\bx_0\sim q(\bx_0)$, $t\sim\mathcal U\{1,\dots,T\}$, $\beps\sim\N(\mathbf 0,\bI)$
- Gradient step on $\nabla_\theta\big\|\beps-\beps_\theta(\sqrt{\bar\alpha_t}\bx_0+\sqrt{1-\bar\alpha_t}\,\beps,t)\big\|^2$
- until converged
- $\bx_T\sim\N(\mathbf 0,\bI)$
- for $t=T,\dots,1$:
- $\bz\sim\N(\mathbf 0,\bI)$ if $t>1$, else $\bz=\mathbf 0$
- $\bx_{t-1}=\dfrac{1}{\sqrt{\alpha_t}}\Big(\bx_t-\dfrac{1-\alpha_t}{\sqrt{1-\bar\alpha_t}}\,\beps_\theta(\bx_t,t)\Big)+\sigma_t\bz$
- return $\bx_0$
$\beps_\theta$로는 시간 $t$를 sinusoidal embedding(Chapter 8의 positional encoding과 같은 방식)으로 받는 U-Net을 쓰며, 낮은 해상도 단계에 self-attention을 넣는다. Training은 한 step이 매우 싸지만, sampling은 $T=1000$번의 network 평가가 필요해 느리다.
18.5Score-based model과의 관계
Gaussian kernel $q(\bx_t\mid\bx_0)$의 score는 $$\nabla_{\bx_t}\log q(\bx_t\mid\bx_0)=-\frac{\bx_t-\sqrt{\bar\alpha_t}\bx_0}{1-\bar\alpha_t}=-\frac{\beps}{\sqrt{1-\bar\alpha_t}}$$ 이다. 따라서 Theorem 17.3에 의해 noise를 예측하는 것은 score를 예측하는 것과 같다. $$\mathbf s_\theta(\bx_t,t)=-\frac{\beps_\theta(\bx_t,t)}{\sqrt{1-\bar\alpha_t}}\approx\nabla_{\bx_t}\log q(\bx_t).$$ $\L_{\text{simple}}$은 noise level $1-\bar\alpha_t$를 갖는 denoising score matching에 가중치 $\lambda=1-\bar\alpha_t$를 준 것이며, NCSN의 $\lambda(\sigma)=\sigma^2$와 같은 선택이다. Sampling 식도 score로 쓰면 $\bx_{t-1}=\frac{1}{\sqrt{\alpha_t}}\big(\bx_t+\beta_t\mathbf s_\theta(\bx_t,t)\big)+\sigma_t\bz$로, Langevin dynamics와 비슷한 "score 방향 이동 + noise"의 형태이다. Song et al.(2021)은 $T\to\infty$ 극한에서 DDPM(variance preserving)과 NCSN(variance exploding)이 각각 하나의 SDE로 표현되며, 같은 marginal을 갖는 deterministic ODE(probability flow ODE)도 존재함을 보였다. 이 연속 시간 관점은 Chapter 20에서 자세히 다룬다.
18.6DDIM: 빠른 deterministic sampling
DDPM loss는 marginal $q(\bx_t\mid\bx_0)$에만 의존하고, joint $q(\bx_{1:T}\mid\bx_0)$가 Markov chain이라는 사실은 쓰지 않는다. 그렇다면 같은 marginal을 갖는 다른(non-Markovian) forward process를 쓰더라도 학습된 $\beps_\theta$를 그대로 쓸 수 있다. 이것이 DDIM(Song, Meng & Ermon, 2021)의 출발점이다.
현재 noise 예측으로 $\bx_0$를 추정한 값을 $$\hat\bx_0(\bx_t)=\frac{\bx_t-\sqrt{1-\bar\alpha_t}\,\beps_\theta(\bx_t,t)}{\sqrt{\bar\alpha_t}}$$ 라 하면, update는 $$\bx_{t-1}=\sqrt{\bar\alpha_{t-1}}\,\hat\bx_0(\bx_t)+\sqrt{1-\bar\alpha_{t-1}-\sigma_t^2}\;\beps_\theta(\bx_t,t)+\sigma_t\bz,\qquad\sigma_t=\eta\sqrt{\frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}}\sqrt{1-\frac{\bar\alpha_t}{\bar\alpha_{t-1}}}.$$
세 항은 각각 "예측한 깨끗한 image", "$\bx_t$를 가리키는 방향", "random noise"이다. $\eta=1$이면 $\sigma_t^2=\tilde\beta_t$가 되어 DDPM과 같은 과정이고($\frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}(1-\alpha_t)=\tilde\beta_t$), $\eta=0$이면 noise 항이 없는 deterministic sampler가 되는데 이것을 DDIM이라 부른다. 이 update는 marginal만 맞추면 되므로 $1,\dots,T$ 전체가 아니라 부분 수열 $\tau_1\lt\tau_2\lt\cdots\lt\tau_S$(예: $S=50$)에서만 수행해도 된다. 같은 model로 10–50배 빠르게 sampling할 수 있다. Deterministic이므로 $\bx_T$가 $\bx_0$의 latent code 역할을 하여, 두 $\bx_T$ 사이를 interpolation하면 의미 있게 변하는 image를 얻는다. $\eta=0$인 DDIM은 probability flow ODE의 discretization으로 볼 수 있다(Chapter 20).
18.7Guidance: 조건부 생성
Classifier guidance
Class $y$를 조건으로 생성하고 싶다. Bayes rule에서 $\log p(\bx_t\mid y)=\log p(\bx_t)+\log p(y\mid\bx_t)-\log p(y)$이므로 $$\nabla_{\bx_t}\log p(\bx_t\mid y)=\nabla_{\bx_t}\log p(\bx_t)+\nabla_{\bx_t}\log p(y\mid\bx_t).$$ 첫째 항은 unconditional diffusion model이, 둘째 항은 noisy image $\bx_t$에서 class를 맞히도록 따로 학습한 classifier $p_\phi(y\mid\bx_t,t)$가 준다(Dhariwal & Nichol, 2021, "Diffusion Models Beat GANs on Image Synthesis"). 깨끗한 image로 학습한 classifier는 noisy input에서 쓸모가 없으므로, classifier도 각 $t$의 noise가 섞인 $\bx_t$로 학습해야 한다. 실제로는 guidance scale $s>0$을 곱해 $$\nabla\log p(\bx_t)+s\,\nabla\log p_\phi(y\mid\bx_t)=\nabla\log\Big[\frac{1}{Z}p(\bx_t)\,p_\phi(y\mid\bx_t)^s\Big]$$ 를 쓴다. $s>1$이면 classifier가 확신하는 영역으로 distribution이 더 날카로워져 다양성을 희생하고 품질(class 일치도)을 높인다. 원 논문의 sampling algorithm은 reverse step의 mean을 classifier gradient 방향으로 옮기는 형태이다.
- Input: class label $y$, gradient scale $s$. $\bx_T\sim\N(\mathbf 0,\bI)$
- for $t=T,\dots,1$:
- $\bmu,\bSigma\leftarrow\bmu_\theta(\bx_t),\bSigma_\theta(\bx_t)$
- $\bx_{t-1}\sim\N\big(\bmu+s\,\bSigma\,\nabla_{\bx_t}\log p_\phi(y\mid\bx_t),\ \bSigma\big)$
- return $\bx_0$
Deterministic sampler(DDIM)에서는 같은 아이디어를 noise 예측에 적용해 $\hat\beps=\beps_\theta(\bx_t,t)-s\sqrt{1-\bar\alpha_t}\,\nabla_{\bx_t}\log p_\phi(y\mid\bx_t)$를 쓴다. 이 논문은 guidance와 개선된 U-Net으로 ImageNet 생성에서 처음으로 GAN(BigGAN)보다 좋은 FID를 보고했다.
Classifier-free guidance
별도의 classifier를 학습하는 것은 번거롭다. Ho & Salimans(2022)는 하나의 network $\beps_\theta(\bx_t,t,y)$를 학습하되, 일정 확률(10–20%)로 조건을 빈 값 $\varnothing$으로 바꿔서 conditional과 unconditional model을 동시에 학습한다. Sampling에서는 $$\tilde\beps=(1+w)\,\beps_\theta(\bx_t,t,y)-w\,\beps_\theta(\bx_t,t,\varnothing)$$ 를 쓴다. Score로 바꾸면($\mathbf s=-\beps/\sqrt{1-\bar\alpha_t}$) $$\tilde{\mathbf s}=\mathbf s(\bx_t\mid y)+w\big(\mathbf s(\bx_t\mid y)-\mathbf s(\bx_t)\big)=\nabla\log p(\bx_t)+(1+w)\,\nabla\log p(y\mid\bx_t)$$ 이므로, 두 score의 차이가 암묵적인 classifier의 gradient $\nabla\log p(y\mid\bx_t)$ 역할을 한다. Classifier guidance에서 $s=1+w$인 경우와 같은 형태이다. 현재 text-to-image model은 거의 모두 이 방식을 쓴다.
18.8Latent diffusion (Stable Diffusion)
$512\times512\times3$ pixel 공간에서 U-Net을 1000번 돌리는 것은 학습과 sampling 모두 비싸다. 그런데 pixel의 대부분은 사람이 거의 인지하지 못하는 고주파 세부이다. Latent diffusion(Rombach et al., 2022)은 인지적으로 중요한 정보를 보존하는 저차원 latent 공간에서 diffusion을 수행한다.
- Autoencoder: encoder $\mathcal E$와 decoder $\mathcal D$를 perceptual loss와 adversarial loss로 먼저 학습한다. Downsampling factor $f=8$이면 $512\times512\times3$ image가 $64\times64\times4$ latent $\bz=\mathcal E(\bx)$가 된다. Latent가 너무 퍼지지 않도록 약한 KL penalty 또는 vector quantization으로 regularize한다.
- Latent diffusion: $\bz$에 대해 DDPM을 학습한다. $\L=\E_{\mathcal E(\bx),y,\beps,t}\big[\|\beps-\beps_\theta(\bz_t,t,\tau_\theta(y))\|^2\big]$.
- Conditioning: 조건 $y$(text 등)를 encoder $\tau_\theta$로 token sequence $\tau_\theta(y)\in\R^{M\times d_\tau}$로 바꾸고, U-Net 중간 feature $\varphi(\bz_t)$에 cross-attention으로 넣는다. $\mathbf Q=\varphi(\bz_t)\bW_Q$, $\mathbf K=\tau_\theta(y)\bW_K$, $\mathbf V=\tau_\theta(y)\bW_V$. Image의 각 위치(query)가 text의 어느 token을 참고할지 정하는 것이다(Chapter 8의 encoder–decoder cross-attention과 같은 구조).
- Sampling: latent 공간에서 $\bz_T\sim\N(\mathbf 0,\bI)$로부터 DDIM 등으로 $\bz_0$를 만들고 $\mathcal D(\bz_0)$로 image를 얻는다.
Stable Diffusion은 이 구조에 CLIP text encoder(Chapter 12)를 $\tau_\theta$로 쓰고 대규모 image–text 쌍으로 학습한 model이다. 공간 크기가 $f^2=64$배 줄어 consumer GPU에서도 학습·추론이 가능해졌다. Semantic map, image, representation 등 다른 조건도 같은 cross-attention 또는 channel concatenation으로 넣을 수 있다.
18.9생성 model의 평가 지표
Likelihood를 계산할 수 없는 model(GAN)이나, 계산할 수 있어도 sample 품질과 잘 맞지 않는 경우가 많아, pre-trained classifier의 feature를 이용한 지표를 주로 쓴다.
ImageNet으로 학습된 Inception-v3 classifier의 예측 $p(y\mid\bx)$와 그 marginal $p(y)=\E_{\bx\sim p_g}[p(y\mid\bx)]$에 대해 $$\mathrm{IS}=\exp\Big(\E_{\bx\sim p_g}\big[\KL\big(p(y\mid\bx)\,\|\,p(y)\big)\big]\Big).$$
각 image는 하나의 class로 확신 있게 분류되고(낮은 $H(y\mid\bx)$), 전체 image는 여러 class에 고르게 퍼질 때(높은 $H(y)$) 크다. 실제로 지수 안의 값은 $H(y)-H(y\mid\bx)=I(\bx;y)$이므로 $1\le\mathrm{IS}\le$ class 수이다. 한계는 real data와 전혀 비교하지 않는다는 것, ImageNet class와 무관한 domain에서는 의미가 없다는 것, class 안의 다양성(같은 class의 똑같은 image만 생성하는 경우)을 잡지 못한다는 것이다.
Real image와 generated image의 Inception-v3 pool feature(2048차원)에 각각 Gaussian $\N(\bmu_r,\bSigma_r)$, $\N(\bmu_g,\bSigma_g)$를 fit하여 $$\mathrm{FID}=\|\bmu_r-\bmu_g\|^2+\tr\Big(\bSigma_r+\bSigma_g-2\big(\bSigma_r\bSigma_g\big)^{1/2}\Big).$$
두 Gaussian 사이의 Wasserstein-2 distance의 제곱이며, 낮을수록 좋다. Real data와 직접 비교하고 품질과 다양성을 모두 반영해 현재 표준 지표이다. 다만 feature를 Gaussian으로 근사한다는 가정이 있고, sample 수에 따라 bias가 있어 보통 10,000–50,000개 sample로 계산하며 서로 다른 sample 수의 FID는 비교하지 않는다. 품질과 다양성을 분리해 보려면 precision/recall 계열 지표를 함께 쓴다.
Reference image가 짝으로 존재하는 task(복원, super-resolution, editing)에서는 pixel이나 feature 수준의 유사도를 쓴다.
| Metric | 정의 | 특징 |
|---|---|---|
| PSNR | $10\log_{10}\big(\mathrm{MAX}^2/\mathrm{MSE}\big)$ dB | Pixel MSE 기반. 높을수록 좋음. 흐린 결과에 관대함 |
| SSIM | Local window의 luminance, contrast, structure 비교의 곱 | $[-1,1]$, 구조적 유사도. PSNR보다 지각에 가까움 |
| LPIPS | Pre-trained network feature 사이의 가중 거리 | 사람의 지각적 유사도 판단과 가장 잘 맞음. 낮을수록 좋음 |
Chapter 19Normalizing Flow
새로 추가한 장 (강의 범위 밖). Dinh et al. 2017; Kingma & Dhariwal 2018; Papamakarios et al. 2017; Chen et al. 2018; Grathwohl et al. 2019
VAE는 likelihood의 lower bound를, GAN은 likelihood 없이 sample만을, diffusion은 다시 lower bound를 다뤘다. Normalizing flow는 정확한 likelihood를 계산할 수 있는 generative model이다. 단순한 distribution을 invertible하고 미분 가능한 함수로 변환하면 변수변환 공식으로 density를 정확히 쓸 수 있다는 것이 전부이다. 이 장에서는 그 공식을 출발점으로 Jacobian determinant를 싸게 계산하는 구조(coupling, autoregressive flow)를 설계하고, 연속 시간으로 확장한 continuous normalizing flow까지 다룬다. 마지막 절은 다음 장의 flow matching으로 이어진다.
19.1Change of variables
$\bz\in\R^d$가 density $p_Z$를 갖고, $g:\R^d\to\R^d$가 diffeomorphism(미분 가능하고 역함수도 미분 가능한 bijection)이며 $f=g^{-1}$이라 하자. $\bx=g(\bz)$의 density는 $$p_X(\bx)=p_Z\big(f(\bx)\big)\,\Big|\det\frac{\partial f(\bx)}{\partial\bx}\Big|=p_Z(\bz)\,\Big|\det\frac{\partial g(\bz)}{\partial\bz}\Big|^{-1},\qquad\bz=f(\bx).$$
임의의 Borel 집합 $B$에 대해 $P(\bx\in B)=P(\bz\in f(B))=\int_{f(B)}p_Z(\bz)\,\dd\bz$. 다변수 적분의 치환 공식으로 $\bz=f(\bx)$를 대입하면 $\int_Bp_Z(f(\bx))|\det J_f(\bx)|\,\dd\bx$이고, 이것이 모든 $B$에 대해 성립하므로 적분 안이 $p_X$이다. 두 번째 표현은 inverse function theorem $J_f(\bx)=J_g(\bz)^{-1}$에서 나온다.
$|\det J|$는 변환이 국소적으로 부피를 몇 배로 늘리는지를 나타낸다. 부피가 늘어난 곳에서는 같은 확률 질량이 넓게 퍼지므로 density가 그만큼 낮아진다. 1차원 예로 $z\sim\N(0,1)$, $x=\mu+\sigma z$이면 $f(x)=(x-\mu)/\sigma$, $|f'|=1/\sigma$이므로 $p_X(x)=\N(x;\mu,\sigma^2)$이다.
여러 변환을 합성한 $g=g_K\circ\cdots\circ g_1$, $\bz_0=\bz$, $\bz_k=g_k(\bz_{k-1})$, $\bx=\bz_K$에 대해 chain rule과 $\det(\mathbf{AB})=\det\mathbf A\det\mathbf B$로 $$\log p_X(\bx)=\log p_Z(\bz_0)-\sum_{k=1}^K\log\Big|\det\frac{\partial g_k}{\partial\bz_{k-1}}\Big|$$ 이다. 단순한 변환을 여러 개 쌓아 복잡한 distribution을 만든다는 뜻에서 "flow", base distribution이 정규화된 density라는 뜻에서 "normalizing"이다. 학습은 이 log-likelihood를 그대로 최대화하는 MLE이다(Chapter 3). VAE, diffusion과 달리 bound가 아니라 정확한 값이다.
표현력에 대한 기본적인 사실은 1차원의 probability integral transform이다. Continuous cdf $F$를 갖는 $X$에 대해 $F(X)\sim\mathrm{Uniform}(0,1)$이고, 거꾸로 $F^{-1}(U)$는 $X$와 같은 분포를 따른다. $d$차원에서도 $x_1$의 marginal cdf, $x_2\mid x_1$의 conditional cdf, …를 차례로 적용하는 triangular map(Knothe–Rosenblatt rearrangement)으로 (적당한 regularity 아래) 임의의 density를 uniform이나 Gaussian으로 보낼 수 있다. 아래의 autoregressive flow가 바로 이 구조이다.
19.2설계 조건
Flow layer $g_k$는 세 가지를 만족해야 한다. (1) Invertible이어야 하고, (2) $\log|\det J|$를 싸게 계산할 수 있어야 하며(일반 $d\times d$ 행렬의 determinant는 $O(d^3)$이고 image에서 $d$는 수십만이다), (3) sampling을 하려면 역변환도 싸야 한다. 동시에 충분히 표현력이 있어야 한다. 일반적인 neural network layer는 (1)부터 만족하지 않는다. 해법의 공통 아이디어는 Jacobian을 triangular로 만드는 것이다. Triangular 행렬의 determinant는 대각 성분의 곱이다.
19.3Coupling layer
$\bz=(\bz_A,\bz_B)$로 차원을 두 부분으로 나누고 $$\bx_A=\bz_A,\qquad\bx_B=\bz_B\odot\exp\big(\mathbf s(\bz_A)\big)+\mathbf t(\bz_A).$$ $\mathbf s,\mathbf t:\R^{|A|}\to\R^{|B|}$는 임의의 neural network이다.
역변환은 $\bz_A=\bx_A$, $\bz_B=(\bx_B-\mathbf t(\bx_A))\odot\exp(-\mathbf s(\bx_A))$이고, $\log|\det\partial\bx/\partial\bz|=\sum_j s_j(\bz_A)$이다.
$\bx_A=\bz_A$이므로 $\mathbf s(\bz_A)=\mathbf s(\bx_A)$, $\mathbf t(\bz_A)=\mathbf t(\bx_A)$를 output에서 바로 계산할 수 있고 둘째 식을 $\bz_B$에 대해 풀면 된다. Jacobian은 $$\frac{\partial\bx}{\partial\bz}=\begin{pmatrix}\bI&\mathbf 0\\[2pt]\dfrac{\partial\bx_B}{\partial\bz_A}&\diag\big(\exp\mathbf s(\bz_A)\big)\end{pmatrix}$$ 로 block lower-triangular이므로 determinant는 대각 block의 determinant 곱 $\prod_j\exp(s_j)$이다.
핵심은 $\mathbf s,\mathbf t$ 자체는 invertible일 필요가 없다는 점이다. 아무리 복잡한 network여도 역변환과 determinant가 공짜로 나온다. 대가는 한 layer가 절반의 차원만 바꾼다는 것이므로, layer마다 $A$와 $B$의 역할을 바꾸거나 차원을 섞으면서 쌓는다. $\mathbf s\equiv\mathbf 0$인 경우가 NICE(Dinh et al., 2015)의 additive coupling으로, determinant가 1인 부피 보존 변환이다.
Image에 쓰는 Glow(Kingma & Dhariwal, 2018)는 한 step을 세 부분으로 구성한다. (1) ActNorm: channel별 affine 변환 $\bx=\mathbf a\odot\bz+\mathbf b$(첫 batch의 통계로 초기화하는 BatchNorm 대체물), log-det $=HW\sum_c\log|a_c|$. (2) Invertible 1×1 convolution: 모든 pixel에서 같은 $C\times C$ 행렬 $\bW$를 channel에 곱한다. Channel 순서를 학습되는 방식으로 섞는 일반화된 permutation이며, log-det $=HW\log|\det\bW|$이다. $\bW=\bP\mathbf L(\mathbf U+\diag\mathbf s)$로 LU 분해해 parameterize하면 determinant가 $\sum_c\log|s_c|$로 $O(C)$이다. (3) Affine coupling. 여기에 해상도를 줄이며 일부 차원을 일찍 latent로 빼내는 multi-scale 구조를 더한다. Flow는 차원을 줄일 수 없으므로 $\bz$의 차원은 $\bx$와 같다.
19.4Autoregressive flow
Chain rule $p(\bx)=\prod_ip(x_i\mid\bx_{\lt i})$의 각 조건부를 Gaussian $\N(\mu_i(\bx_{\lt i}),e^{2\alpha_i(\bx_{\lt i})})$로 두면, 이는 $$x_i=\mu_i(\bx_{\lt i})+e^{\alpha_i(\bx_{\lt i})}z_i,\qquad z_i\iid\N(0,1)$$ 이라는 변환과 같다. $z_i$는 $x_i$와 $\bx_{\lt i}$에만 의존하므로 $\partial\bz/\partial\bx$는 lower-triangular이고 $\log|\det\partial\bz/\partial\bx|=-\sum_i\alpha_i$이다. 이렇게 autoregressive model을 flow로 본 것이 masked autoregressive flow(MAF; Papamakarios et al., 2017)이다. $\mu_i,\alpha_i$는 MADE(masked autoencoder, weight에 mask를 곱해 $i$번째 output이 $\bx_{\lt i}$에만 의존하게 만든 network)로 한 번의 forward pass에 모두 계산한다. 같은 변환을 반대로, 즉 $\mu_i,\alpha_i$를 $\bz_{\lt i}$의 함수로 두면 inverse autoregressive flow(IAF; Kingma et al., 2016)가 된다.
| MAF | IAF | |
|---|---|---|
| Shift/scale의 입력 | $\bx_{\lt i}$ (data 쪽) | $\bz_{\lt i}$ (noise 쪽) |
| Density 계산 $p(\bx)$ | 한 번의 pass (병렬) | $d$번의 순차 pass |
| Sampling | $d$번의 순차 pass | 한 번의 pass (병렬) |
| 적합한 용도 | Density estimation, MLE 학습 | 빠른 sampling, VAE의 posterior $q_\phi(\bz\mid\bx)$ |
Coupling layer는 autoregressive flow에서 조건부 구조를 두 block으로 단순화한 특수한 경우로, density와 sampling이 모두 한 번의 pass로 가능한 대신 layer 하나의 표현력이 약하다. Chapter 26의 GPT도 discrete token에 대한 autoregressive model이라는 점에서 같은 족보에 있다.
19.5Discrete data와 bits per dimension
Image pixel은 $\{0,\dots,255\}$의 정수이다. Continuous density model을 discrete 점에 그대로 fit하면 density를 점 위에 무한히 집중시켜 likelihood를 무한대로 보낼 수 있다. 그래서 dequantization, 즉 $\mathbf u\sim\mathrm{Uniform}[0,1)^d$를 더한 $\tilde\bx=\bx+\mathbf u$에 대해 학습한다. 이때 continuous model $p$가 정의하는 discrete model $P(\bx)=\int_{[0,1)^d}p(\bx+\mathbf u)\,\dd\mathbf u$에 대해 $$\log P(\bx)=\log\E_{\mathbf u}\big[p(\bx+\mathbf u)\big]\ge\E_{\mathbf u}\big[\log p(\bx+\mathbf u)\big]$$ (Jensen)이므로, dequantized data의 continuous log-likelihood는 discrete log-likelihood의 lower bound이다(Theis et al., 2016). 성능은 흔히 bits per dimension $-\log_2P(\bx)/d$로 보고한다. Pixel을 $[0,1)$로 scale한 $\by=\tilde\bx/256$의 density $p_Y$로 학습했다면 $p_{\tilde X}(\tilde\bx)=p_Y(\by)/256^d$이므로 bpd $=\big(-\log p_Y(\by)+d\log256\big)/(d\log2)$이다. 8 bit보다 얼마나 압축했는지로 읽을 수 있으며, CIFAR-10에서 RealNVP는 3.49, Glow는 3.35 bits/dim을 보고했다.
19.6Continuous normalizing flow
Layer를 무한히 잘게 쪼개면 변환은 ODE가 된다. Vector field $\bv_\theta(\bz,t)$에 대해 $$\frac{\dd\bz(t)}{\dd t}=\bv_\theta\big(\bz(t),t\big),\qquad\bz(0)\sim p_0,\qquad\bx=\bz(1).$$ ODE의 해 map $\bz(0)\mapsto\bz(1)$은 ($\bv_\theta$가 Lipschitz이면) diffeomorphism이고 역변환은 ODE를 시간 역방향으로 푸는 것이다. ResNet의 $\bx_{l+1}=\bx_l+F(\bx_l)$을 Euler step으로 본 neural ODE(Chen et al., 2018)와 같은 관점이다. 이 경우 determinant 대신 trace가 나온다.
$\bz(t)$가 위 ODE를 따르고 $p_t$가 $\bz(t)$의 density이면, 궤적을 따라 $$\frac{\dd}{\dd t}\log p_t\big(\bz(t)\big)=-\nabla\cdot\bv_\theta\big(\bz(t),t\big)=-\tr\Big(\frac{\partial\bv_\theta}{\partial\bz}\big(\bz(t),t\big)\Big).$$ 따라서 $\log p_1(\bx)=\log p_0(\bz(0))-\int_0^1\tr\big(\partial\bv_\theta/\partial\bz\big)\,\dd t$이다.
Vector field를 따라 움직이는 질량의 보존은 continuity equation $\partial_tp_t+\nabla\cdot(p_t\bv)=0$으로 쓰인다(임의의 고정된 영역에서 질량의 변화율은 경계를 통과하는 flux와 같다는 것을 divergence theorem으로 국소화한 것). 궤적을 따른 total derivative는 $$\frac{\dd}{\dd t}p_t(\bz(t))=\partial_tp_t+\nabla p_t\cdot\bv=-\nabla\cdot(p_t\bv)+\nabla p_t\cdot\bv=-p_t\,\nabla\cdot\bv$$ 이다($\nabla\cdot(p\bv)=\nabla p\cdot\bv+p\nabla\cdot\bv$). 양변을 $p_t$로 나누면 된다.
$\bv_\theta$에는 구조 제약이 전혀 없다. 대신 $\tr(\partial\bv/\partial\bz)$를 정확히 계산하려면 $d$번의 backward pass가 필요하다. FFJORD(Grathwohl et al., 2019)는 Hutchinson trace estimator를 쓴다. $\E[\boldsymbol\varepsilon]=\mathbf 0$, $\E[\boldsymbol\varepsilon\boldsymbol\varepsilon^\top]=\bI$인 random vector(Gaussian 또는 Rademacher)에 대해 $$\E_{\boldsymbol\varepsilon}\big[\boldsymbol\varepsilon^\top\mathbf J\boldsymbol\varepsilon\big]=\tr\big(\mathbf J\,\E[\boldsymbol\varepsilon\boldsymbol\varepsilon^\top]\big)=\tr\mathbf J$$ 이고, $\boldsymbol\varepsilon^\top\mathbf J$는 vector–Jacobian product 한 번으로 계산된다. Chapter 17의 sliced score matching과 같은 기법이다. 그래도 학습의 매 step마다 ODE를 수치적으로 풀어야 하므로 비싸다. 다음 장의 flow matching은 ODE를 풀지 않고 $\bv_\theta$를 regression으로 학습하는 방법이다.
19.7장점과 한계
- 정확한 likelihood. Model 비교, density estimation, 압축, 그리고 VAE의 유연한 posterior(IAF)나 prior로 쓸 수 있다. 다만 likelihood가 높다고 sample이 좋거나 out-of-distribution을 잘 탐지하는 것은 아니다. CIFAR-10으로 학습한 Glow가 처음 보는 SVHN image에 더 높은 likelihood를 준다는 결과가 유명하다(Nalisnick et al., 2019). Likelihood는 배경의 단순함 같은 low-level 통계에 크게 좌우된다.
- 차원 보존. Bijection이어야 하므로 latent 차원이 data 차원과 같다. 저차원 manifold 근처에 있는 data(Chapter 17의 manifold hypothesis)를 표현하려면 Jacobian이 거의 singular해져야 한다.
- 위상 제약. Diffeomorphism은 연결된 집합을 연결된 집합으로 보낸다. Unimodal Gaussian에서 서로 떨어진 mode 여럿을 만들려면 그 사이에서 density를 거의 0으로 짜내는 극단적인 변환이 필요하다.
- Sample 품질. 같은 계산량에서 diffusion이나 GAN보다 sample 품질이 낮다. 그러나 continuous flow라는 관점은 diffusion의 probability flow ODE와 flow matching으로 이어져, 현재의 대형 image·video 생성 model의 기반이 되었다.
Chapter 20연속 시간 생성 model: SDE, Probability Flow, Flow Matching
새로 추가한 장 (강의 범위 밖). Song et al. 2021; Anderson 1982; Karras et al. 2022; Lipman et al. 2023; Liu et al. 2023
Chapter 17의 NCSN은 noise level $\sigma_1>\cdots>\sigma_L$을, Chapter 18의 DDPM은 step $t=1,\dots,T$를 이산적으로 두었다. Song et al.(2021)은 step을 무한히 잘게 나눈 극한에서 두 model이 모두 stochastic differential equation(SDE)으로 표현되고, 생성은 그 SDE를 시간 역방향으로 푸는 것임을 보였다. 이 관점에서 DDIM은 같은 marginal을 갖는 ODE를 푸는 것이 되고, Chapter 19의 continuous normalizing flow와 만난다. 마지막으로 그 ODE의 vector field를 simulation 없이 regression으로 학습하는 flow matching을 유도한다. 이 장의 수학은 Itô calculus의 기초를 쓰지만, 필요한 것은 Fokker–Planck equation 하나뿐이다.
20.1Forward SDE
$\mathbf B_t$를 $d$차원 Brownian motion이라 하자. 독립 증분 $\mathbf B_{t+\Delta}-\mathbf B_t\sim\N(\mathbf 0,\Delta\,\bI)$를 갖는 연속 process이다. Itô SDE $$\dd\bx=\mathbf f(\bx,t)\,\dd t+g(t)\,\dd\mathbf B_t$$ 는 작은 $\Delta$에 대해 $\bx_{t+\Delta}\approx\bx_t+\mathbf f(\bx_t,t)\Delta+g(t)\sqrt\Delta\,\beps$, $\beps\sim\N(\mathbf 0,\bI)$라는 뜻이다(Euler–Maruyama discretization). $\mathbf f$는 drift, $g$는 diffusion coefficient이다. Noise 항이 $\sqrt\Delta$에 비례한다는 것이 일반 ODE와의 본질적인 차이이다. Chapter 17의 Langevin dynamics가 이미 이런 SDE의 discretization이었다.
앞의 두 model은 다음 두 SDE의 discretization이다.
- Variance exploding (VE) SDE. $\dd\bx=\sqrt{\dd[\sigma^2(t)]/\dd t}\;\dd\mathbf B_t$. Drift가 없고 noise만 쌓이므로 $\bx_t\mid\bx_0\sim\N(\bx_0,(\sigma^2(t)-\sigma^2(0))\bI)$이다. NCSN의 perturbation $\bx_i=\bx_{i-1}+\sqrt{\sigma_i^2-\sigma_{i-1}^2}\,\beps$가 이것의 discretization이다.
- Variance preserving (VP) SDE. $\dd\bx=-\frac12\beta(t)\bx\,\dd t+\sqrt{\beta(t)}\,\dd\mathbf B_t$. DDPM의 $\bx_i=\sqrt{1-\beta_i}\,\bx_{i-1}+\sqrt{\beta_i}\,\beps$에서 $\beta_i=\beta(t)\Delta$로 두면 $\sqrt{1-\beta(t)\Delta}=1-\frac12\beta(t)\Delta+O(\Delta^2)$이므로 Euler–Maruyama step과 1차까지 같다.
VP SDE에서 $\bar\alpha(t)=\exp\big(-\int_0^t\beta(s)\,\dd s\big)$라 하면 $$\bx_t\mid\bx_0\sim\N\big(\sqrt{\bar\alpha(t)}\,\bx_0,\ (1-\bar\alpha(t))\bI\big).$$
Drift가 $\bx$에 linear이므로 $\bx_t\mid\bx_0$는 Gaussian이다(Gaussian 증분의 linear 결합의 극한). Mean $\mathbf m(t)=\E[\bx_t\mid\bx_0]$은 SDE의 기댓값을 취하면 ($\E[\dd\mathbf B_t]=\mathbf 0$) $\dot{\mathbf m}=-\frac12\beta\mathbf m$이므로 $\mathbf m(t)=\sqrt{\bar\alpha(t)}\bx_0$. 각 좌표의 variance $v(t)$는 Euler–Maruyama step에서 $v(t+\Delta)=(1-\frac12\beta\Delta)^2v(t)+\beta\Delta$이므로 $\Delta\to0$에서 $\dot v=-\beta v+\beta$, $v(0)=0$이고 해는 $v(t)=1-\bar\alpha(t)$이다.
이산 DDPM의 $\bar\alpha_t=\prod_{s\le t}(1-\beta_s)\approx\exp(-\sum_s\beta_s)$와 정확히 대응한다. 즉 Chapter 18의 forward marginal(Proposition 18.2)은 이 명제의 이산 버전이다. 이 장에서는 data가 $t=0$, noise가 $t=T$(또는 1)에 있는 Chapter 18의 시간 방향을 따른다.
20.2Fokker–Planck equation과 reverse-time SDE
SDE를 따르는 입자의 density $p_t(\bx)$는 다음 PDE를 만족한다.
$$\partial_tp_t(\bx)=-\nabla\cdot\big(\mathbf f(\bx,t)\,p_t(\bx)\big)+\frac12g(t)^2\,\Delta p_t(\bx),$$ $\Delta=\nabla\cdot\nabla$는 Laplacian이다.
첫 항은 drift를 따라 질량이 이동하는 것(Chapter 19의 continuity equation), 둘째 항은 noise에 의한 확산(heat equation)이다. 생성에 필요한 것은 이 과정을 거꾸로 돌리는 것이다.
Forward SDE의 marginal이 $p_t$일 때, $t=T$에서 $p_T$로 시작해 시간을 거꾸로 진행하는 SDE $$\dd\bx=\Big[\mathbf f(\bx,t)-g(t)^2\,\nabla_\bx\log p_t(\bx)\Big]\dd t+g(t)\,\dd\bar{\mathbf B}_t$$ ($\dd t\lt0$, $\bar{\mathbf B}_t$는 역방향 Brownian motion)는 모든 $t$에서 같은 marginal $p_t$를 갖는다.
역방향 과정에 필요한 미지의 양은 각 시점의 score $\nabla\log p_t$뿐이다. 이것을 Chapter 17의 denoising score matching으로 학습한다. $$\min_\theta\ \E_{t\sim\mathcal U(0,T)}\Big[\lambda(t)\,\E_{\bx_0}\E_{\bx_t\mid\bx_0}\big\|\mathbf s_\theta(\bx_t,t)-\nabla_{\bx_t}\log p_{t\mid0}(\bx_t\mid\bx_0)\big\|^2\Big].$$ VP SDE이면 $\nabla\log p_{t\mid0}=-\beps/\sqrt{1-\bar\alpha(t)}$이고, $\lambda(t)=1-\bar\alpha(t)$로 두면 Chapter 18의 $\L_{\text{simple}}$과 같은 ε-prediction loss가 된다. 학습된 score로 reverse SDE를 Euler–Maruyama로 풀면 DDPM의 ancestral sampling과 1차까지 같은 update가 나온다.
20.3Probability flow ODE
같은 marginal $p_t$를 갖는 과정은 하나가 아니다. Noise가 전혀 없는 ODE도 있다.
$$\frac{\dd\bx}{\dd t}=\mathbf f(\bx,t)-\frac12g(t)^2\nabla_\bx\log p_t(\bx)$$ 를 $\bx_0\sim p_0$에서 출발해 풀면 $\bx_t$의 marginal은 forward SDE와 같은 $p_t$이다. 더 일반적으로 모든 $\lambda\ge0$에 대해 SDE $$\dd\bx=\Big[\mathbf f-\frac{1+\lambda^2}{2}g^2\nabla\log p_t\Big]\dd t+\lambda g\,\dd\mathbf B_t$$ 도 같은 marginal을 갖는다($\lambda=1$은 forward SDE 자신, $\lambda=0$은 ODE).
$\nabla p_t=p_t\nabla\log p_t$이므로 $\frac12g^2\Delta p_t=\nabla\cdot\big(\frac12g^2p_t\nabla\log p_t\big)$이다. 이를 Fokker–Planck equation에 넣으면 $$\partial_tp_t=-\nabla\cdot\Big(\big[\mathbf f-\tfrac12g^2\nabla\log p_t\big]p_t\Big),$$ 즉 vector field $\tilde{\mathbf f}=\mathbf f-\frac12g^2\nabla\log p_t$에 대한 continuity equation이다. 이 ODE를 따르는 입자의 density도 같은 PDE를 따르고 초기 조건이 같으므로 marginal이 같다. 일반 $\lambda$의 SDE에 대한 Fokker–Planck equation도 확산 항 $\frac12\lambda^2g^2\Delta p_t=\nabla\cdot(\frac12\lambda^2g^2p_t\nabla\log p_t)$를 drift로 옮기면 같은 continuity equation이 된다.
이 정리가 주는 것은 다음과 같다.
- Deterministic sampling. $\bx_T\sim\N(\mathbf 0,\bI)$에서 ODE를 $t=T\to0$으로 풀면 data distribution에서의 sample을 얻는다. 같은 noise는 같은 image로 가므로 $\bx_T$가 image의 latent code가 되고, interpolation과 editing이 가능하다. Chapter 18의 DDIM($\eta=0$)은 VP SDE의 probability flow ODE를 특정한 변수 변환 아래에서 1차 방법으로 푼 것이다. DDIM의 $\eta$는 위 정리의 $\lambda$처럼 같은 marginal을 갖는 process들 사이를 잇는 parameter이다.
- 빠른 ODE solver. ODE이므로 Heun(2차 Runge–Kutta), DPM-Solver 같은 고차 solver를 쓸 수 있다. Karras et al.(2022, EDM)은 noise schedule과 solver를 정리해 수십 step 이하로 높은 품질을 얻었다.
- 정확한 likelihood. 이 ODE는 Chapter 19의 continuous normalizing flow이므로 Theorem 19.4로 $\log p_0(\bx)$를 계산할 수 있다. Diffusion model이 ELBO가 아닌 정확한 likelihood를 보고할 수 있는 이유이다.
- Predictor–corrector. SDE 쪽에서는 reverse SDE의 한 step(predictor) 뒤에 같은 $t$의 score로 Langevin dynamics를 몇 step(corrector) 돌려 marginal의 오차를 교정할 수 있다. Chapter 17의 annealed Langevin dynamics가 corrector만 쓰는 경우이다.
20.4Flow matching
Probability flow ODE의 vector field는 score로 정해진다. 거꾸로, noise distribution과 data distribution을 잇는 vector field를 처음부터 직접 학습하면 어떨까? Chapter 19의 continuous normalizing flow는 maximum likelihood로 학습하려면 매 step ODE를 풀어야 했다. Flow matching(Lipman et al., 2023)은 이를 regression 문제로 바꾼다. 이 절에서는 flow matching 문헌의 관례에 따라 시간 방향을 바꿔 $t=0$을 noise, $t=1$을 data로 둔다.
Noise $\bx_0\sim p_0=\N(\mathbf 0,\bI)$와 data $\bx_1\sim q$를 독립으로 뽑아 직선으로 잇는 경로 $$\bx_t=(1-t)\,\bx_0+t\,\bx_1,\qquad t\in[0,1]$$ 를 생각하자. $\bx_t$의 marginal을 $p_t$라 하면 $p_0$은 Gaussian, $p_1=q$이다. 이 marginal path를 만드는 ODE $\dot\bx=\mathbf u_t(\bx)$가 있다면 그것으로 noise를 data로 보낼 수 있다. 개별 경로의 속도는 $\dot\bx_t=\bx_1-\bx_0$로 간단하지만, 같은 점 $\bx$를 지나는 경로가 여러 개이므로 marginal vector field는 그 평균이어야 한다.
$\mathbf u_t(\bx)=\E\big[\bx_1-\bx_0\mid\bx_t=\bx\big]$로 정의하면, ODE $\dot\bx=\mathbf u_t(\bx)$는 $\bx(0)\sim p_0$에서 출발할 때 모든 $t$에서 marginal $p_t$를 갖는다.
$\bx_1$을 고정하면 $\bx_t\mid\bx_1\sim p_t(\cdot\mid\bx_1)=\N(t\bx_1,(1-t)^2\bI)$이고, 이 conditional path는 vector field $\mathbf u_t(\bx\mid\bx_1)=(\bx_1-\bx)/(1-t)$가 만든다(점 $\bx$에서 시작해 남은 시간 $1-t$ 동안 $\bx_1$로 곧게 가는 속도; $\bx=\bx_t$이면 $\bx_1-\bx_0$와 같다). 즉 각 $\bx_1$에 대해 continuity equation $\partial_tp_t(\bx\mid\bx_1)=-\nabla\cdot\big(p_t(\bx\mid\bx_1)\mathbf u_t(\bx\mid\bx_1)\big)$이 성립한다. 양변을 $q(\bx_1)$로 적분하면 $$\partial_tp_t(\bx)=-\nabla\cdot\Big(\int p_t(\bx\mid\bx_1)\mathbf u_t(\bx\mid\bx_1)q(\bx_1)\,\dd\bx_1\Big)=-\nabla\cdot\big(p_t(\bx)\,\mathbf u_t(\bx)\big),$$ 여기서 $\mathbf u_t(\bx)=\int\mathbf u_t(\bx\mid\bx_1)\frac{p_t(\bx\mid\bx_1)q(\bx_1)}{p_t(\bx)}\dd\bx_1=\E[\mathbf u_t(\bx\mid\bx_1)\mid\bx_t=\bx]=\E[\bx_1-\bx_0\mid\bx_t=\bx]$이다. 따라서 $p_t$는 $\mathbf u_t$에 대한 continuity equation을 만족하고, 같은 초기 조건에서 출발한 ODE의 marginal과 같다.
$\mathbf u_t(\bx)$는 data distribution을 알아야 계산할 수 있으므로 직접 regression target으로 쓸 수 없다. 그러나 Chapter 17의 denoising score matching과 정확히 같은 trick이 통한다.
$$\L_{\text{FM}}(\theta)=\E_{t,\bx_t}\big\|\bv_\theta(\bx_t,t)-\mathbf u_t(\bx_t)\big\|^2,\qquad\L_{\text{CFM}}(\theta)=\E_{t,\bx_0,\bx_1}\big\|\bv_\theta(\bx_t,t)-(\bx_1-\bx_0)\big\|^2$$ ($t\sim\mathcal U[0,1]$, $\bx_t=(1-t)\bx_0+t\bx_1$)는 $\theta$와 무관한 상수만큼만 다르다. 따라서 두 loss의 gradient와 minimizer가 같고, 최적해는 $\bv^\ast=\mathbf u_t$이다.
두 제곱을 전개하면 $\E\|\bv_\theta\|^2$ 항은 같고, target의 제곱 항은 $\theta$와 무관하다. Cross term은 tower property로 $$\E\big[\bv_\theta(\bx_t,t)^\top(\bx_1-\bx_0)\big]=\E\Big[\bv_\theta(\bx_t,t)^\top\E[\bx_1-\bx_0\mid\bx_t,t]\Big]=\E\big[\bv_\theta(\bx_t,t)^\top\mathbf u_t(\bx_t)\big]$$ 로 같다. 최적해는 conditional expectation이 squared error를 최소화하는 predictor라는 사실, 즉 $\E\|\mathbf Y-h(\mathbf X)\|^2$이 $h(\mathbf X)=\E[\mathbf Y\mid\mathbf X]$에서 최소라는 사실에서 나온다.
- Training. repeat: $\bx_1\sim$ data, $\bx_0\sim\N(\mathbf 0,\bI)$, $t\sim\mathcal U[0,1]$, $\bx_t=(1-t)\bx_0+t\bx_1$; gradient step on $\|\bv_\theta(\bx_t,t)-(\bx_1-\bx_0)\|^2$
- Sampling. $\bx\sim\N(\mathbf 0,\bI)$; ODE $\dot\bx=\bv_\theta(\bx,t)$를 $t=0\to1$로 풀기 (Euler: $\bx\leftarrow\bx+\frac1N\bv_\theta(\bx,t)$, $N$ step)
Training은 DDPM만큼 단순하다. Simulation도, likelihood 계산도, noise schedule도 필요 없다. 같은 algorithm을 Liu et al.(2023)은 rectified flow, Albergo & Vanden-Eijnden(2023)은 stochastic interpolant라는 이름으로 독립적으로 제안했다.
Diffusion과의 관계. 직선 대신 $\bx_t=\alpha_t\bx_1+\sigma_t\bx_0$ 꼴의 Gaussian path를 쓰면 diffusion의 forward process(시간 방향만 반대)와 같은 형태가 된다. 이때 marginal vector field는 score의 affine 함수이다. Tweedie's formula(Proposition 17.4)에 의해 $\E[\bx_0\mid\bx_t]=-\sigma_t\nabla\log p_t(\bx_t)$이고 $\E[\bx_1\mid\bx_t]=(\bx_t-\sigma_t\E[\bx_0\mid\bx_t])/\alpha_t$이므로 $$\mathbf u_t(\bx)=\dot\alpha_t\E[\bx_1\mid\bx]+\dot\sigma_t\E[\bx_0\mid\bx]=\frac{\dot\alpha_t}{\alpha_t}\bx-\Big(\dot\sigma_t-\frac{\dot\alpha_t\sigma_t}{\alpha_t}\Big)\sigma_t\nabla\log p_t(\bx)$$ 이다. 따라서 ε-prediction, score-prediction, $\bx_0$-prediction, velocity-prediction은 모두 같은 정보를 다르게 parameterize한 것이고, Gaussian path를 쓰는 flow matching은 diffusion model의 probability flow ODE를 학습하는 것과 같다. 차이는 path(schedule)의 선택과 loss의 시간 가중치에 있다. 직선 path는 ODE의 궤적을 덜 휘게 만들어 적은 step으로도 정확히 풀 수 있는 경향이 있다.
Reflow와 few-step 생성. 학습된 ODE로 만든 (noise, sample) 쌍 $(\bx_0,\hat\bx_1)$을 새 coupling으로 삼아 flow matching을 다시 학습하면(reflow) 궤적이 점점 직선에 가까워지고, 극한에서는 Euler step 하나로 생성할 수 있다. 궤적 위의 모든 점을 같은 끝점으로 보내도록 학습하는 consistency model(Song et al., 2023), adversarial loss를 더한 distillation(Chapter 16 끝) 등도 같은 목표, 즉 ODE를 몇 step 만에 푸는 것을 겨냥한다.
Stable Diffusion 3, FLUX 같은 최근의 text-to-image model과 다수의 video 생성 model은 latent 공간(Chapter 18의 latent diffusion)에서 rectified flow로 학습한다. 조건부 생성은 diffusion과 같은 방식으로 한다. $\bv_\theta(\bx,t,y)$를 조건과 함께 학습하고 sampling 때 classifier-free guidance를 velocity에 적용한다.
20.5정리
| 관점 | 학습하는 것 | 생성 과정 | 대표 model |
|---|---|---|---|
| Score-based (VE SDE) | $\nabla\log p_\sigma$, multi-level DSM | Annealed Langevin / reverse SDE | NCSN (Ch. 17) |
| Diffusion (VP SDE) | $\beps_\theta$ (= score), ELBO ≈ DSM | Reverse SDE (ancestral) | DDPM (Ch. 18) |
| Probability flow | 위와 같음 | Deterministic ODE | DDIM, EDM |
| Flow matching | Velocity $\bv_\theta$, regression | Deterministic ODE | Rectified flow, SD3 |
| Continuous normalizing flow | $\bv_\theta$, exact MLE | Deterministic ODE | FFJORD (Ch. 19) |
모두 "단순한 distribution에서 data distribution으로 가는 marginal path $p_t$를 정하고, 그 path를 실현하는 동역학을 local한 regression으로 배운다"는 같은 틀에 있다. Path를 어떻게 정하고(SDE의 noise schedule 또는 interpolation), 동역학을 무엇으로 parameterize하는가(score 또는 velocity)가 model 사이의 차이이다.
Uncertainty와 Evaluation
Chapter 21Uncertainty와 Calibration
새로 추가한 장 (강의 범위 밖). Guo et al. 2017; Gal & Ghahramani 2016; Lakshminarayanan et al. 2017; Vovk et al. 2005; Angelopoulos & Bates 2023
Classifier가 "고양이일 확률 0.97"이라고 말할 때 그 숫자를 믿어도 될까? Point estimate만 내던 회귀에서 신뢰구간을 붙이는 것이 통계학의 기본이듯, deep learning model의 예측에도 불확실성을 붙여야 의사결정에 쓸 수 있다. 이 장에서는 불확실성을 aleatoric과 epistemic으로 나누고, Bayesian neural network의 근사(Laplace, MC dropout, deep ensemble), 확률 예측이 맞는지를 재는 calibration과 proper scoring rule, 가장 간단하면서 효과적인 보정법인 temperature scaling, 그리고 분포 가정 없이 coverage를 보장하는 conformal prediction을 다룬다.
21.1두 종류의 불확실성
예측의 불확실성에는 성격이 다른 두 원천이 있다.
- Aleatoric uncertainty: data 자체의 noise. 같은 $\bx$에서도 $y$가 확률적으로 변한다(측정 오차, 본질적으로 모호한 image). Data를 아무리 모아도 줄지 않는다. Model 안에서는 $p_\theta(y\mid\bx)$의 퍼짐(예측 variance, softmax의 entropy)으로 표현된다.
- Epistemic uncertainty: model(parameter)에 대한 지식의 부족. Training data가 적거나 없는 영역에서 크고, data가 늘면 준다. Parameter의 posterior $p(\theta\mid\mathcal D)$의 퍼짐으로 표현된다.
Bayesian predictive distribution $p(y\mid\bx,\mathcal D)=\int p(y\mid\bx,\theta)\,p(\theta\mid\mathcal D)\,\dd\theta$에서 두 성분은 정확히 분해된다.
(a) Regression: $\mu_\theta(\bx)=\E[y\mid\bx,\theta]$, $\sigma^2_\theta(\bx)=\Var(y\mid\bx,\theta)$이면 $$\Var(y\mid\bx,\mathcal D)=\underbrace{\E_{\theta\mid\mathcal D}\big[\sigma_\theta^2(\bx)\big]}_{\text{aleatoric}}+\underbrace{\Var_{\theta\mid\mathcal D}\big(\mu_\theta(\bx)\big)}_{\text{epistemic}}.$$ (b) Classification: $\bar\bp=\E_{\theta\mid\mathcal D}[\bp_\theta(\bx)]$이면 $$H(\bar\bp)=\underbrace{\E_{\theta\mid\mathcal D}\big[H(\bp_\theta(\bx))\big]}_{\text{aleatoric}}+\underbrace{I(y;\theta\mid\bx,\mathcal D)}_{\text{epistemic}}.$$
(a)는 law of total variance $\Var(y)=\E[\Var(y\mid\theta)]+\Var(\E[y\mid\theta])$를 posterior 아래에서 적용한 것이다. (b)는 mutual information의 정의 $I(y;\theta)=H(y)-H(y\mid\theta)$에서 $H(y)=H(\bar\bp)$, $H(y\mid\theta)=\E_\theta H(\bp_\theta)$를 넣은 것이다(Chapter 3).
(b)의 epistemic 항은 여러 model이 서로 다른 class를 확신할 때 커진다. 각 model은 확신하지만(작은 entropy) 의견이 엇갈리는 상황이다. 이 양은 active learning에서 label을 붙일 sample을 고르는 기준(BALD)으로도 쓰인다.
21.2Heteroscedastic regression
Chapter 3에서 Gaussian likelihood로부터 MSE를 유도할 때 variance $\sigma^2$를 상수로 두었다. 이를 input에 따라 바뀌게 하면 aleatoric uncertainty를 직접 학습할 수 있다. Network가 $\mu_\theta(\bx)$와 $s_\theta(\bx)=\log\sigma^2_\theta(\bx)$를 함께 출력하고 negative log-likelihood $$\ell(\theta;\bx,y)=\frac12s_\theta(\bx)+\frac{(y-\mu_\theta(\bx))^2}{2e^{s_\theta(\bx)}}+\text{const}$$ 를 최소화한다. $\log\sigma^2$를 출력하는 이유는 양수 제약을 없애고 수치적으로 안정하게 하기 위해서이다(VAE의 encoder와 같다). 각 $\bx$에서 $s$에 대해 최소화하면 $\sigma^2(\bx)=\E[(y-\mu(\bx))^2\mid\bx]$로, 예측 오차의 조건부 기댓값을 배운다. 주의할 점은 $\sigma^2$가 큰 sample의 mean 항 gradient가 $1/\sigma^2$로 작아져서, 학습 초기에 맞추기 어려운 영역을 "noise가 크다"고 선언해 버리고 mean을 덜 학습하는 경향이 있다는 것이다. Mean을 먼저 MSE로 학습한 뒤 variance를 학습하거나, loss에 $\sigma^{2\beta}$(stop-gradient)를 곱하는 $\beta$-NLL(Seitzer et al., 2022) 같은 보완책이 있다.
21.3Bayesian neural network의 근사
Parameter에 prior $p(\theta)$를 두면 posterior는 $p(\theta\mid\mathcal D)\propto p(\mathcal D\mid\theta)p(\theta)$이다. Chapter 4에서 본 weight decay 학습은 이 posterior의 mode(MAP)를 찾는 것이었다. Predictive distribution에 필요한 것은 mode가 아니라 posterior 전체이지만, parameter가 수백만 개인 network에서 이를 정확히 계산할 수는 없다. 대표적인 근사는 다음과 같다.
Laplace approximation
MAP $\hat\theta$ 주위에서 negative log-posterior를 2차 Taylor 전개하면 posterior는 Gaussian $$p(\theta\mid\mathcal D)\approx\N\big(\hat\theta,\ \mathbf H^{-1}\big),\qquad\mathbf H=-\nabla^2_\theta\log p(\theta\mid\mathcal D)\big|_{\hat\theta}$$ 으로 근사된다. Chapter 1에서 MLE의 asymptotic distribution이 $\N(\theta_0,\mathcal I^{-1}/n)$(Theorem 1.9)이었던 것과 같은 구조이며, $\mathbf H$는 observed Fisher information에 prior의 precision을 더한 것이다. 전체 Hessian은 너무 크므로 Kronecker 분해(K-FAC), 대각 근사, 또는 마지막 layer의 weight에만 Laplace를 적용하는 last-layer Laplace를 쓴다. 이미 학습된 model에 사후적으로 붙일 수 있다는 것이 큰 장점이다(Daxberger et al., 2021).
Variational inference와 MC dropout
Chapter 15의 variational inference를 parameter에 적용해 $q_\phi(\theta)$로 posterior를 근사하고 ELBO $\E_q[\log p(\mathcal D\mid\theta)]-\KL(q_\phi(\theta)\|p(\theta))$를 최대화할 수 있다(Bayes by Backprop; Blundell et al., 2015). Reparameterization trick을 그대로 쓰지만 parameter 수가 두 배가 되고 학습이 불안정하다.
Gal & Ghahramani(2016)는 dropout을 넣고 weight decay로 학습한 network가, weight의 각 column이 확률적으로 0이 되는 특정한 variational distribution에 대한 variational inference로 해석될 수 있음을 보였다. 그렇다면 test 때에도 dropout을 켠 채로 $T$번 forward pass를 하여 $$\hat\bp(\bx)=\frac1T\sum_{t=1}^T\bp_{\theta_t}(\bx),\qquad\theta_t\sim q(\theta)\ (\text{dropout mask})$$ 로 predictive distribution을, 그 분산이나 위의 mutual information으로 epistemic uncertainty를 추정할 수 있다. 이를 MC dropout이라 한다. 구현이 간단해서 널리 쓰이지만, dropout rate가 posterior의 폭을 고정하므로 data 양에 따라 epistemic uncertainty가 줄어드는 성질이 약하고, 근사의 질에 대한 비판도 있다.
Deep ensemble
같은 architecture의 network $M$개를 서로 다른 random initialization(과 data 순서)으로 독립적으로 학습하고 예측을 평균한다(Lakshminarayanan et al., 2017). $$\hat\bp(\bx)=\frac1M\sum_{m=1}^M\bp_{\theta_m}(\bx).$$ Bayesian 근사로 설계된 것은 아니지만, non-convex loss의 서로 다른 basin(mode)에서 해를 하나씩 뽑으므로 하나의 mode 주변만 보는 Laplace나 VI보다 posterior의 다양성을 더 잘 반영한다(Fort et al., 2019). 실험적으로 정확도, calibration, distribution shift 아래의 불확실성 모두에서 가장 강력한 baseline이며, 보통 $M=5$ 정도로 충분하다. 단점은 학습과 추론 비용이 $M$배라는 것이다. 한 번의 학습 경로에서 여러 checkpoint를 모으는 snapshot ensemble, SGD iterate의 평균과 공분산으로 Gaussian posterior를 만드는 SWAG(Maddox et al., 2019) 등이 비용을 줄인 변형이다.
21.4Calibration
예측 확률이 실제 빈도와 일치하는 것을 calibration이라 한다.
Classifier의 예측 class를 $\hat Y$, 그 confidence를 $\hat P=\max_k\hat p_k(X)$라 하자. 모든 $c\in[0,1]$에 대해 $$P\big(\hat Y=Y\ \big|\ \hat P=c\big)=c$$ 이면 (top-label) calibrated라 한다. 예를 들어 confidence 0.8로 예측한 sample들 중 80%가 맞아야 한다.
유한 sample에서는 confidence를 $B$개 구간(bin) $\mathcal B_1,\dots,\mathcal B_B$로 나눠 각 bin의 정확도와 평균 confidence를 비교한다. 이를 그린 것이 reliability diagram이고, 차이를 sample 비율로 가중 평균한 것이 expected calibration error $$\mathrm{ECE}=\sum_{b=1}^B\frac{|\mathcal B_b|}{n}\Big|\mathrm{acc}(\mathcal B_b)-\mathrm{conf}(\mathcal B_b)\Big|$$ 이다. ECE는 bin 수와 경계에 따라 값이 달라지고 sample이 적은 bin에서 bias가 있으므로, 같은 binning으로 계산한 값끼리만 비교해야 한다.
Guo et al.(2017)은 현대의 깊은 network(ResNet 등)가 LeNet 시절의 얕은 network보다 정확하지만 훨씬 overconfident하다는 것을 보였다. Accuracy가 포화된 뒤에도 training을 계속하면 NLL은 training data에서 logit의 크기를 키우는 방식으로 계속 줄어드는데, 이것이 test data에서의 과신으로 이어진다. 큰 model, BatchNorm, 약한 weight decay가 이 경향을 키운다.
21.5Proper scoring rule
확률 예측 $\bp$를 결과 $y$로 평가하는 함수 $S(\bp,y)$(작을수록 좋음)가 참 distribution $\bq$ 아래에서 기대 점수를 $\bp=\bq$일 때 최소로 하면 proper, 그 최소가 유일하면 strictly proper scoring rule이라 한다. 정직하게 믿는 확률을 말하는 것이 최선이 되도록 만드는 평가 기준이다.
Log score $S(\bp,y)=-\log p_y$와 Brier score $S(\bp,y)=\|\bp-\be_y\|^2=\sum_k(p_k-\ind[y=k])^2$에 대해 $$\E_{y\sim\bq}[-\log p_y]=H(\bq)+\KL(\bq\|\bp),\qquad\E_{y\sim\bq}\|\bp-\be_y\|^2=\|\bp-\bq\|^2+\big(1-\|\bq\|^2\big).$$ 둘 다 $\bp=\bq$에서만 최소이다.
첫 식은 Chapter 3의 cross-entropy 분해이다. 둘째 식은 $\E_y[\be_y]=\bq$, $\|\be_y\|^2=1$을 써서 $\E\|\bp-\be_y\|^2=\|\bp\|^2-2\bp^\top\bq+1=\|\bp-\bq\|^2+1-\|\bq\|^2$. 두 경우 모두 $\bp$에 의존하는 부분이 $\bp=\bq$에서만 0인 divergence이다.
NLL(log score)과 Brier score는 calibration과 정확도를 함께 평가한다. Accuracy와 ECE는 proper scoring rule이 아니다. 예를 들어 모든 input에 class prior를 그대로 출력하는 classifier는 완벽하게 calibrated(ECE $=0$)이지만 아무 쓸모가 없다. 그래서 calibration은 ECE와 함께 NLL이나 Brier score로 보고하는 것이 좋다. Brier score는 다시 reliability(calibration 오차) − resolution(예측이 base rate에서 얼마나 벗어나 정보를 주는가) + uncertainty(data 자체의 불확실성)로 분해된다(Murphy, 1973).
21.6Temperature scaling
Guo et al.(2017)이 제안한 가장 단순한 사후 보정법은 logit $\bz$를 하나의 scalar $T>0$으로 나누는 것이다. $$\hat\bp=\softmax(\bz/T),\qquad\hat T=\argmin_{T>0}\ \sum_{i\in\text{valid}}\Big[-\frac{z_{i,y_i}}{T}+\log\sum_ke^{z_{ik}/T}\Big].$$ Model은 그대로 두고 validation set에서 parameter 하나만 NLL로 fit한다. $T>1$이면 distribution이 평평해져(confidence 감소) overconfidence를 교정한다. Chapter 12의 knowledge distillation, Chapter 26의 decoding에 나오는 temperature와 같은 연산이다.
(a) 모든 $T>0$에 대해 $\argmax_k\softmax(\bz/T)_k=\argmax_kz_k$이므로 accuracy가 변하지 않는다.
(b) Validation NLL은 $\tau=1/T$에 대해 convex이다.
(a) $x\mapsto x/T$와 softmax가 모두 순서를 보존한다. (b) 각 항 $-\tau z_y+\log\sum_ke^{\tau z_k}$에서 첫 항은 $\tau$에 linear이고, 둘째 항은 log-sum-exp(convex)와 $\tau$의 linear map의 합성이므로 convex이다.
더 유연한 방법으로는 class마다 다른 scale과 bias를 두는 vector scaling, binary classifier에서 logit에 logistic regression $\sigma(az+b)$를 fit하는 Platt scaling, monotone한 임의의 함수를 fit하는 isotonic regression이 있다. 그러나 parameter가 늘수록 validation set에 overfit하기 쉬워서, 실제로는 temperature scaling이 가장 안정적인 경우가 많다. 중요한 한계는 calibration이 학습 distribution 안에서만 보장된다는 것이다. Distribution shift가 생기면 calibrated model도 다시 과신한다(Ovadia et al., 2019). 이런 상황에서는 deep ensemble이 상대적으로 강하다.
21.7Conformal prediction
지금까지의 방법은 model이 맞다는 가정 아래의 불확실성이다. Conformal prediction은 model이 틀렸더라도, data가 exchangeable하다는 가정만으로 정해진 확률 이상으로 정답을 포함하는 prediction set을 만든다. 어떤 model에도 사후적으로 붙일 수 있다.
- 학습된 model과 그것을 학습할 때 쓰지 않은 calibration set $\{(\bx_i,y_i)\}_{i=1}^n$, 허용 오차 $\alpha$를 준비한다.
- Nonconformity score $s_i=s(\bx_i,y_i)$를 계산한다. 예: regression이면 $|y_i-\hat\mu(\bx_i)|$, classification이면 $1-\hat p_{y_i}(\bx_i)$.
- $\hat q=$ $\{s_i\}$ 중 $\lceil(n+1)(1-\alpha)\rceil$번째로 작은 값.
- 새 input $\bx$에 대해 $\mathcal C(\bx)=\{y:s(\bx,y)\le\hat q\}$를 출력한다. Regression이면 $[\hat\mu(\bx)-\hat q,\ \hat\mu(\bx)+\hat q]$.
$(\bx_1,y_1),\dots,(\bx_n,y_n),(\bx_{n+1},y_{n+1})$이 exchangeable이면 $$P\big(y_{n+1}\in\mathcal C(\bx_{n+1})\big)\ge1-\alpha.$$ Score에 동점이 없으면(continuous) $P\big(y_{n+1}\in\mathcal C(\bx_{n+1})\big)\le1-\alpha+\frac1{n+1}$이기도 하다.
Model은 calibration data와 무관하게 고정되어 있으므로 score $s_1,\dots,s_{n+1}$도 exchangeable이다. 따라서 $s_{n+1}$이 $n+1$개 중 몇 번째로 작은지(rank)는 동점이 없을 때 $\{1,\dots,n+1\}$ 위에서 uniform이고, 동점이 있으면 작은 쪽으로 기울어질 뿐이다. $k=\lceil(n+1)(1-\alpha)\rceil$이라 하면 $y_{n+1}\in\mathcal C\iff s_{n+1}\le\hat q=s_{(k)}^{(1:n)}\iff s_{n+1}$의 rank가 $k$ 이하이다. 이 확률은 $k/(n+1)\ge1-\alpha$ 이상이고, 동점이 없으면 정확히 $k/(n+1)\lt1-\alpha+1/(n+1)$이다.
보장은 calibration set과 test point의 결합 확률에 대한 것이다. 예를 들어 $n=500$, $\alpha=0.1$로 calibration set을 새로 뽑아 가며 20,000번 반복한 simulation에서 coverage는 0.902로 이론 구간 $[0.9,\ 0.902]$ 안에 있었다. Model의 질은 coverage가 아니라 set의 크기에 나타난다. 나쁜 model도 coverage는 지키지만 interval이 넓다.
한계는 두 가지이다. (1) 보장은 marginal coverage, 즉 $\bx$에 대해 평균 낸 것이다. 특정 subgroup이나 어려운 input에서는 coverage가 낮을 수 있다. 모든 $\bx$에서 조건부 coverage를 보장하는 것은 일반적으로 불가능하다. Score를 잘 설계하면 근사적으로 개선된다. Regression에서 $\alpha/2$, $1-\alpha/2$ quantile을 pinball loss로 학습하고 그 바깥으로 벗어난 정도를 score로 쓰는 conformalized quantile regression(CQR; Romano et al., 2019)은 noise가 큰 곳에서 넓은 interval을 준다. Classification에서는 확률을 큰 순서로 누적하는 APS score가 쓰인다. (2) Exchangeability가 깨지는 distribution shift나 시계열에서는 보장이 사라지며, 이를 위한 weighted conformal, online conformal 방법이 연구되고 있다.
21.8Out-of-distribution과 selective prediction
Training distribution에서 크게 벗어난 input(out-of-distribution, OOD)을 알아차리는 것도 불확실성의 문제이다. 가장 단순한 baseline은 maximum softmax probability가 낮으면 OOD로 판단하는 것이다(Hendrycks & Gimpel, 2017). 그 밖에 logit의 log-sum-exp(energy score), penultimate feature 공간에서 class별 Gaussian을 fit한 Mahalanobis distance, ensemble의 불일치가 쓰인다. Chapter 19에서 보았듯 generative model의 likelihood는 OOD 점수로 믿을 만하지 않다.
실무에서 불확실성의 가장 직접적인 쓰임은 selective prediction이다. Confidence가 threshold $\tau$보다 낮은 input에서는 예측을 보류하고 사람에게 넘긴다. $\tau$를 바꿔 가며 예측한 비율(coverage)과 그 안에서의 오류율(risk)을 그린 risk–coverage curve로 평가한다. 불확실성 추정이 좋을수록 낮은 coverage에서 risk가 빠르게 준다.
정리하면, 실용적인 출발점은 (1) 단일 model에 temperature scaling을 하고 NLL, Brier, ECE를 함께 보고하며, (2) 계산 여유가 있으면 deep ensemble을, (3) 정해진 coverage가 필요하면 그 위에 conformal prediction을 얹는 것이다.
Chapter 22평가와 실험 설계
새로 추가한 장 (강의 범위 밖). Hastie, Tibshirani & Friedman 2009 (ESL Ch. 7); Bates, Hastie & Tibshirani 2023; DeLong et al. 1988; Dietterich 1998
"새 model의 test accuracy가 0.3%p 올랐다"는 주장은 언제 믿을 수 있을까? Deep learning 논문의 결과 표는 통계학의 관점에서 보면 하나의 estimate이고, estimate에는 bias와 variance가 있다. 이 장은 model 성능을 측정하는 일을 하나의 estimation 문제로 보고 정리한다. Data 분할과 leakage, cross-validation이 실제로 추정하는 것, classification metric과 prevalence의 관계, ROC/AUC와 precision–recall, metric의 신뢰구간, 두 model의 비교, 그리고 재현 가능한 보고 방법을 다룬다.
22.1무엇을 추정하는가
학습된 model $\hat f$의 성능 지표는 test set으로 계산한 $\hat R_{\text{test}}(\hat f)$이고, 우리가 알고 싶은 것은 보통 둘 중 하나이다.
- 이 model의 성능 $R(\hat f)=\E[\ell(\hat f(X),Y)\mid\hat f]$: 배포할 바로 그 model이 새 data에서 낼 성능. Test set이 학습과 독립이면 $\hat R_{\text{test}}$는 이것의 unbiased estimate이고, 분산은 test set 크기로 정해진다.
- 이 algorithm의 성능 $\E_{\mathcal D}[R(\hat f_{\mathcal D})]$: 같은 architecture와 학습 절차를 크기 $n$의 새 training set에 적용했을 때의 기대 성능. "방법 A가 방법 B보다 좋다"는 연구의 주장은 대개 이것에 관한 것이다. 여기에는 test set의 randomness뿐 아니라 training data, initialization, data 순서의 randomness가 모두 들어간다.
두 번째 양을 한 번의 학습과 하나의 test set으로 추정하면 variance가 과소평가된다. 이 구분이 이후 모든 절의 바탕이다.
22.2Data 분할과 leakage
Chapter 4에서 train, validation, test의 역할을 정했다. 원칙은 하나이다. Test set의 정보는 어떤 경로로도 학습이나 model 선택에 들어가면 안 된다. 이 원칙이 깨지는 것을 data leakage라 하며, 실제로는 다음 형태로 자주 일어난다.
- 단위의 불일치. 한 사람(사용자, 환자, 화자)이나 한 문서에서 나온 sample이 여러 개일 때 sample 단위로 무작위 분할하면 같은 사람의 data가 train과 test에 동시에 들어간다. Model은 그 사람의 특징을 외워 test 성능이 부풀려진다. 분할은 일반화하려는 단위(사람, 기관, 문서)로 해야 한다(group split).
- 시간. 미래를 예측하는 model인데 무작위로 분할하면 과거 예측에 미래 정보가 쓰인다. 시간 순서대로 분할하거나 rolling-origin 평가를 한다.
- 전처리. Normalization 통계, feature selection, oversampling, PCA 등을 전체 data로 fit한 뒤 분할하면 test 정보가 새어 들어간다. 모든 전처리는 training fold 안에서만 fit해야 한다. 고차원 data에서 전체 data로 feature를 고른 뒤 cross-validation을 하면, label과 무관한 random feature만으로도 높은 정확도가 나올 수 있다(Ambroise & McLachlan, 2002).
- 중복. Web에서 모은 dataset에는 거의 같은 image나 text가 train과 test에 함께 있는 경우가 흔하다. 대형 language model에서는 benchmark 문제가 pre-training corpus에 포함되는 contamination이 문제가 된다.
- Test set의 반복 사용. 같은 test set을 보며 수많은 model과 hyperparameter를 비교하면, test set이 사실상 validation set이 되어 그 위에서 overfitting한다(adaptive overfitting). Recht et al.(2019)은 CIFAR-10과 ImageNet의 test set을 같은 절차로 새로 만들어 평가했는데, 기존 model의 정확도가 ImageNet에서 11–14%p 떨어졌다. 다만 model 간 순위는 대체로 유지되어, 하락의 주원인은 adaptive overfitting보다 새 data의 분포 차이로 해석되었다.
22.3Cross-validation
Data가 적을 때는 하나의 분할에 의존하는 대신 $K$-fold cross-validation을 쓴다. Data를 $K$개 fold로 나누고, 각 $k$에 대해 fold $k$를 제외한 data로 학습해 fold $k$에서 평가한 뒤 평균한다. $$\widehat{\mathrm{CV}}=\frac1n\sum_{k=1}^K\sum_{i\in\text{fold }k}\ell\big(\hat f^{(-k)}(\bx_i),y_i\big).$$
- 무엇을 추정하는가. $\widehat{\mathrm{CV}}$는 특정 model $\hat f$(전체 data로 학습한 것)의 성능보다는 크기 $n(1-1/K)$의 training set에 대한 algorithm의 기대 성능을 추정한다(Bates, Hastie & Tibshirani, 2023). Training set이 조금 작으므로 약간 비관적인 bias가 있다.
- Variance. Fold별 추정치는 training set을 공유하므로 서로 상관되어 있다. 그래서 fold별 값의 표본분산으로 만든 naive한 신뢰구간은 너무 좁다. 위 논문은 nested CV로 이를 보정하는 방법을 제시한다.
- Model 선택. CV로 hyperparameter를 고른 뒤 같은 CV 점수를 성능으로 보고하면 선택 과정의 낙관적 bias가 남는다. 바깥 loop로 성능을, 안쪽 loop로 hyperparameter를 정하는 nested cross-validation을 쓴다.
- Stratified, group $K$-fold. Class 비율을 fold마다 유지하거나(stratified), 같은 group이 한 fold에만 있게 한다(group).
Deep learning에서는 학습 비용 때문에 고정된 train/validation/test 분할을 주로 쓴다. 그 경우에도 algorithm의 성능을 주장하려면 random seed를 바꿔 여러 번 학습해야 한다(아래 절).
22.4Classification metric과 prevalence
Binary classification에서 threshold를 정하면 결과는 confusion matrix로 요약된다.
| 실제 positive | 실제 negative | |
|---|---|---|
| 예측 positive | TP | FP (type I error) |
| 예측 negative | FN (type II error) | TN |
| Metric | 정의 | 확률로 쓰면 |
|---|---|---|
| Sensitivity, recall, TPR | TP/(TP+FN) | $P(\hat Y=1\mid Y=1)$ |
| Specificity, TNR | TN/(TN+FP) | $P(\hat Y=0\mid Y=0)$ |
| Precision, PPV | TP/(TP+FP) | $P(Y=1\mid\hat Y=1)$ |
| NPV | TN/(TN+FN) | $P(Y=0\mid\hat Y=0)$ |
| Accuracy | (TP+TN)/전체 | $P(\hat Y=Y)$ |
| Balanced accuracy | (sensitivity + specificity)/2 | class별 정확도의 평균 |
| F1 | 2·precision·recall/(precision+recall) | precision과 recall의 조화평균 |
Sensitivity와 specificity는 실제 class를 조건으로 하므로 prevalence $\pi=P(Y=1)$와 무관한 classifier의 성질이다. Precision과 NPV는 예측을 조건으로 하므로 prevalence에 따라 달라진다.
$$\mathrm{PPV}=\frac{\mathrm{sens}\cdot\pi}{\mathrm{sens}\cdot\pi+(1-\mathrm{spec})(1-\pi)},\qquad\mathrm{NPV}=\frac{\mathrm{spec}\cdot(1-\pi)}{\mathrm{spec}\cdot(1-\pi)+(1-\mathrm{sens})\,\pi}.$$
Bayes rule: $P(Y=1\mid\hat Y=1)=\frac{P(\hat Y=1\mid Y=1)P(Y=1)}{P(\hat Y=1\mid Y=1)P(Y=1)+P(\hat Y=1\mid Y=0)P(Y=0)}$. NPV도 같다.
Sensitivity와 specificity가 모두 0.95인 detector라도 $\pi=0.01$인 집단에 적용하면 PPV는 $0.0095/(0.0095+0.0495)\approx0.16$이다. Positive 판정의 84%가 오경보이다. 균형 잡힌 test set에서 측정한 precision을 실제 prevalence가 다른 환경에 그대로 옮기면 안 되는 이유이다. 같은 이유로 class imbalance가 심할 때 accuracy는 거의 정보가 없다. 모든 것을 negative로 예측해도 accuracy가 $1-\pi$이다.
22.5ROC curve와 AUC
Classifier가 score $S$(예: positive class의 확률)를 내고 threshold $c$ 이상을 positive로 판정한다고 하자. $c$를 바꾸면서 $(\mathrm{FPR}(c),\mathrm{TPR}(c))=(P(S\ge c\mid Y=0),\,P(S\ge c\mid Y=1))$를 그린 것이 ROC curve, 그 아래 넓이가 AUC이다.
$S_1\sim S\mid Y=1$, $S_0\sim S\mid Y=0$을 독립으로 뽑으면 $$\mathrm{AUC}=P(S_1>S_0)+\tfrac12P(S_1=S_0).$$ 따라서 empirical AUC는 Mann–Whitney $U$ statistic을 $n_1n_0$으로 나눈 것과 같다: $\widehat{\mathrm{AUC}}=\frac1{n_1n_0}\sum_{i:y_i=1}\sum_{j:y_j=0}\big(\ind[s_i>s_j]+\frac12\ind[s_i=s_j]\big)$.
Continuous score(동점 없음)로 보인다. $G_y(c)=P(S_y\ge c)$라 하면 ROC는 $(G_0(c),G_1(c))$이고, $c$가 $+\infty$에서 $-\infty$로 갈 때 FPR은 0에서 1로 증가한다. $\mathrm{AUC}=\int_0^1\mathrm{TPR}\,\dd(\mathrm{FPR})=\int G_1(c)\,f_0(c)\,\dd c$ ($\dd G_0(c)=-f_0(c)\dd c$이고 적분 방향이 바뀌어 부호가 상쇄된다). 이는 $\E_{S_0}[P(S_1\ge S_0\mid S_0)]=P(S_1>S_0)$이다. Empirical 버전은 empirical distribution에 같은 논리를 적용한 것이고, 동점은 ROC의 대각선 조각에 해당해 $\frac12$이 붙는다.
즉 AUC는 "무작위로 고른 positive가 무작위로 고른 negative보다 높은 score를 받을 확률"이다. Score의 monotone 변환에 불변이므로 순위만 평가하고, 확률이 calibrated인지는 전혀 보지 않는다(Chapter 21). Chapter 24의 C-index는 censoring이 있는 survival data로 이를 일반화한 것이다. 예를 들어 $S_0\sim\N(0,1)$, $S_1\sim\N(\Delta,1)$인 binormal model에서는 $S_1-S_0\sim\N(\Delta,2)$이므로 $\mathrm{AUC}=\Phi(\Delta/\sqrt2)$이다.
Imbalance가 심하고 positive class의 성능이 관심일 때는 precision–recall curve와 그 아래 넓이를 요약한 average precision(AP)이 더 많은 정보를 준다. ROC는 prevalence와 무관하지만, PR curve는 위 명제에 따라 prevalence에 직접 의존한다. 무작위 classifier의 PR curve는 높이 $\pi$의 수평선이다.
Threshold 선택
ROC는 threshold와 무관한 요약이지만 실제 배포에는 threshold 하나가 필요하다. Youden index $J=\mathrm{sens}+\mathrm{spec}-1$을 최대화하는 것은 두 오류의 비용이 같고 prevalence가 1/2일 때의 선택이다. 일반적으로는 decision theory로 정한다.
False positive의 비용이 $c_{\text{FP}}$, false negative의 비용이 $c_{\text{FN}}$이고 $p(\bx)=P(Y=1\mid\bx)$를 정확히 알면, 기대 비용을 최소화하는 결정은 $$\hat y(\bx)=\ind\Big[p(\bx)\ge\frac{c_{\text{FP}}}{c_{\text{FP}}+c_{\text{FN}}}\Big].$$
$\bx$에서 positive로 판정하면 기대 비용은 $(1-p)c_{\text{FP}}$, negative로 판정하면 $p\,c_{\text{FN}}$이다. 앞의 것이 작거나 같을 조건을 정리하면 된다.
이 규칙은 $p(\bx)$가 calibrated일 때만 의미가 있다. 그래서 threshold를 확률로 해석하려면 Chapter 21의 calibration이 먼저 필요하다. 또 threshold를 정하는 data와 최종 성능을 보고하는 data는 분리해야 한다. Test set에서 고른 threshold의 sensitivity와 specificity는 낙관적으로 편향된다.
22.6Regression metric
MSE(또는 RMSE)는 Gaussian likelihood에 대응하며 conditional mean을 목표로 한다. MAE는 Laplace likelihood에 대응하고 conditional median을 목표로 하므로 outlier에 덜 민감하다(Chapter 3의 Gaussian–MSE 유도와 같은 논리이다). $R^2=1-\mathrm{MSE}/\Var(y)$는 평균만 예측하는 baseline 대비 줄인 오차의 비율이며, test set에서는 음수가 될 수 있다. 상대 오차 MAPE는 $y$가 0에 가까우면 발산하고 과대예측과 과소예측을 비대칭으로 벌하므로 주의해서 쓴다.
22.7Metric의 불확실성
Test set이 유한하므로 모든 metric에는 sampling error가 있다. Accuracy는 binomial proportion이므로 test set 크기 $n$에서 standard error가 $\sqrt{\hat a(1-\hat a)/n}$이다. $n=1000$, $\hat a=0.90$이면 SE $\approx0.0095$로 95% 신뢰구간이 약 $\pm1.9$%p이다. 0.3%p 차이를 주장하려면 훨씬 큰 test set이나 아래의 paired 비교가 필요하다. 비율이 0이나 1에 가까울 때는 Wald 구간보다 Wilson score interval이 낫다.
AUC, F1, AP처럼 분포가 복잡한 metric에는 bootstrap을 쓴다.
- Test set $\{(\bx_i,y_i)\}_{i=1}^n$과 model의 예측을 고정한다.
- for $b=1,\dots,B$ (예: $B=2000$): $\{1,\dots,n\}$에서 복원추출로 $n$개를 뽑아 metric $\hat\theta^{\ast b}$를 계산한다. (Group 구조가 있으면 group 단위로 뽑는다. Class 비율을 유지하려면 class별로 뽑는다.)
- $\{\hat\theta^{\ast b}\}$의 2.5%, 97.5% quantile을 95% 신뢰구간으로 보고한다.
이 구간은 test set sampling에 의한 불확실성만 반영한다. 즉 "이 model의 성능"에 대한 구간이다. "이 algorithm의 성능"에 대한 불확실성에는 training의 randomness가 더해져야 한다. AUC에는 U-statistic 이론에 기반한 DeLong et al.(1988)의 closed-form variance도 널리 쓰인다.
22.8두 model 비교하기
같은 test set에서 두 model을 비교할 때는 sample별로 짝지어진(paired) 구조를 이용해야 검정력이 높다. 두 model의 정확도가 각각 0.90이어도 틀리는 sample이 대부분 겹치는 경우와 전혀 겹치지 않는 경우는 다르다.
- McNemar test. Model A만 맞힌 sample 수를 $b$, B만 맞힌 수를 $c$라 하면, 두 model의 정확도가 같다는 귀무가설 아래 $(b-c)^2/(b+c)\approx\chi^2_1$이다. 둘 다 맞히거나 둘 다 틀린 sample은 차이에 대한 정보가 없으므로 쓰이지 않는다.
- Paired bootstrap. 같은 resample에서 두 model의 metric 차이 $\hat\theta_A^{\ast b}-\hat\theta_B^{\ast b}$를 계산해 그 분포의 구간이 0을 포함하는지 본다. 어떤 metric에도 쓸 수 있다.
- Correlated AUC. 같은 sample에서 계산한 두 AUC의 차이는 DeLong test로 검정한다.
Algorithm을 비교하려면 training의 randomness도 고려해야 한다. Bouthillier et al.(2021)은 data 분할, weight initialization, data 순서, data augmentation의 randomness가 각각 benchmark 결과에 무시할 수 없는 분산을 만들고, 흔히 보고되는 개선 폭이 이 분산과 비슷한 크기임을 보였다. 최소한의 원칙은 다음과 같다.
- 여러 seed(가능하면 5개 이상)로 학습해 mean과 standard deviation(또는 신뢰구간)을 보고한다. 가장 좋은 seed 하나만 보고하지 않는다.
- Baseline에도 제안 방법과 같은 hyperparameter 탐색 예산을 준다. 제안 방법만 열심히 튜닝하면 차이는 방법이 아니라 튜닝 노력에서 온다.
- 여러 dataset이나 설정에서 비교할 때는 multiple comparison을 고려하고, 통계적 유의성과 함께 효과 크기가 실질적으로 의미 있는지를 말한다.
- Data가 작아 CV를 쓴다면 fold 간 상관을 고려한 검정(예: 5×2 CV paired $t$-test; Dietterich, 1998)이나 nested CV를 쓴다.
22.9보고 checklist
| 항목 | 보고할 내용 |
|---|---|
| Data | 출처, 크기, class 분포, 분할 단위(sample/group/시간)와 방법, 중복 제거 여부 |
| 전처리 | 어떤 data로 fit했는지(training fold만), augmentation |
| Model 선택 | Hyperparameter 탐색 공간과 예산, 선택에 쓴 data와 기준, baseline에 준 예산 |
| 학습의 randomness | Seed 수, mean ± sd |
| Metric | Threshold 무관 지표(AUC, AP, NLL)와 threshold 의존 지표, threshold를 정한 방법과 data |
| 불확실성 | Test metric의 신뢰구간(bootstrap 등), model 비교는 paired 검정 |
| Calibration | Reliability diagram, ECE, Brier/NLL (확률을 쓰는 경우) |
| Subgroup와 shift | 주요 subgroup별 성능, 외부 data(다른 기관·시기·장비)에서의 성능 |
마지막 항목은 특히 중요하다. 같은 출처에서 무작위로 나눈 test set은 같은 분포에서의 성능만 말해 준다. 다른 환경에서도 성능이 유지되는지는 독립적으로 수집한 외부 data로만 확인할 수 있으며, 실제 배포 전의 평가는 이것을 기준으로 해야 한다.
Chapter 23Distribution Shift와 Domain Adaptation
새로 추가한 장 (강의 범위 밖). Shimodaira 2000; Saerens et al. 2002; Lipton et al. 2018; Ben-David et al. 2010; Ganin et al. 2016; Sagawa et al. 2020
지금까지의 거의 모든 결과는 training data와 test data가 같은 distribution에서 나왔다는 가정 위에 있었다. 실제 배포에서는 이 가정이 깨진다. 다른 기관, 다른 장비, 다른 시기, 다른 사용자 집단의 data는 학습 data와 조금씩 다르고, 그 차이가 성능을 떨어뜨린다. Chapter 22가 "외부 data로 검증하라"로 끝났다면, 이 장은 그 결과를 이해하고 대응하는 이론이다. Shift의 종류를 joint distribution의 분해로 정의하고, 각각에 대해 무엇을 보정할 수 있고 무엇은 보정할 수 없는지를 정리한다.
23.1Shift의 분류
Source(학습) distribution을 $p_S(\bx,y)$, target(배포) distribution을 $p_T(\bx,y)$라 하자. Joint distribution은 두 가지로 분해할 수 있고, 어느 성분이 바뀌는가에 따라 shift를 나눈다.
| 종류 | 바뀌는 것 | 유지되는 것 | 예 |
|---|---|---|---|
| Covariate shift | $p(\bx)$ | $p(y\mid\bx)$ | 다른 연령 분포의 사용자, 다른 조명·해상도의 image |
| Label shift (prior shift) | $p(y)$ | $p(\bx\mid y)$ | 같은 질환이 다른 유병률로 나타나는 지역, 계절에 따른 class 비율 변화 |
| Concept shift | $p(y\mid\bx)$ | (없음) | 진단 기준이나 labeling 지침의 변경, 사기 수법의 진화 |
| Subpopulation shift | Subgroup의 비율 | Group 안의 distribution | 학습 data에 드문 subgroup이 배포 환경에서 많아짐 |
어느 분해가 맞는지는 data가 생성되는 인과 방향과 관련이 있다. $y$가 $\bx$를 낳는 경우(질병이 영상 소견을 만드는 것처럼 원인이 label 쪽에 있는 경우)에는 $p(\bx\mid y)$가 안정적이어서 label shift가 자연스럽고, $y$가 $\bx$의 함수로 정해지는 경우(사람이 image를 보고 label을 붙이는 경우)에는 $p(y\mid\bx)$가 안정적이어서 covariate shift가 자연스럽다. Image 장비가 바뀌는 것처럼 $p(\bx\mid y)$ 자체가 바뀌는 경우는 두 분해 모두에서 벗어나며, 아래의 representation 정렬이나 test-time adaptation이 다루는 대상이다.
23.2Covariate shift와 importance weighting
$p_S(y\mid\bx)=p_T(y\mid\bx)$이고 $p_S(\bx)>0$인 곳에서만 $p_T(\bx)>0$이면, $w(\bx)=p_T(\bx)/p_S(\bx)$에 대해 $$R_T(f)=\E_{p_T}[\ell(f(\bx),y)]=\E_{p_S}\big[w(\bx)\,\ell(f(\bx),y)\big].$$
$\int\!\!\int\ell\,p_T(y\mid\bx)p_T(\bx)\,\dd y\,\dd\bx=\int\!\!\int\ell\,p_S(y\mid\bx)\frac{p_T(\bx)}{p_S(\bx)}p_S(\bx)\,\dd y\,\dd\bx$. Chapter 13의 importance sampling과 같은 식이다.
따라서 source data에 $w(\bx_i)$로 가중한 empirical risk를 최소화하면 target risk의 unbiased estimate를 최적화한다. $w$는 두 density를 따로 추정할 필요 없이 classifier 하나로 얻을 수 있다. Source와 target의 unlabeled input을 섞어 "이 input이 target에서 왔는가"를 맞히는 domain classifier $c(\bx)=P(T\mid\bx)$를 학습하면, Bayes rule로 $$w(\bx)=\frac{p_T(\bx)}{p_S(\bx)}=\frac{n_S}{n_T}\cdot\frac{c(\bx)}{1-c(\bx)}$$ 이다(Chapter 16의 GAN discriminator가 density ratio를 추정한 것과 같은 원리).
두 가지 주의점이 있다. 첫째, weight의 분산이다. Target이 source의 꼬리에 있으면 소수 sample이 매우 큰 weight를 받아 추정이 불안정하다. Kish의 effective sample size $n_{\text{eff}}=(\sum_iw_i)^2/\sum_iw_i^2$로 진단하고, weight를 자르거나(clipping) 평탄화($w^\lambda$, $0\lt\lambda\lt1$)해 bias와 variance를 절충한다. 둘째, model이 올바르게 지정되어(well-specified) 있으면 weighting이 필요 없다. $p(y\mid\bx)$를 정확히 표현하는 model은 어느 $\bx$ 분포에서 학습해도 같은 해로 수렴하기 때문이다. Weighting은 model이 틀렸을 때, target 영역에서 가장 좋은 근사를 고르게 하는 역할을 한다(Shimodaira, 2000). 큰 neural network는 학습 data를 거의 완벽하게 맞히므로 weighting의 효과가 작아지는 경우가 많고, 대신 early stopping이나 regularization과 함께 쓸 때 효과가 있다.
23.3Label shift
Label shift에서는 $p(\bx\mid y)$가 같고 prior만 $\pi^S_y\to\pi^T_y$로 바뀐다. 이 경우 source에서 학습한 posterior를 Bayes rule로 정확히 보정할 수 있다.
$$p_T(y\mid\bx)=\frac{p_S(y\mid\bx)\,\pi^T_y/\pi^S_y}{\sum_{y'}p_S(y'\mid\bx)\,\pi^T_{y'}/\pi^S_{y'}}.$$
$p_T(y\mid\bx)\propto p(\bx\mid y)\pi^T_y=\frac{p_S(y\mid\bx)p_S(\bx)}{\pi^S_y}\pi^T_y$이고, $p_S(\bx)$는 $y$와 무관하므로 정규화로 사라진다.
Chapter 14의 logit adjustment는 $\pi^T$가 균등인 특수한 경우이다. 문제는 target prior $\pi^T$를 모른다는 것이다. Target의 label 없는 data만으로 이를 추정하는 두 방법이 있다.
- EM(Saerens et al., 2002): $\pi^T$를 latent mixture weight로 보고, E-step에서 위 식으로 target posterior $\hat p_T(y\mid\bx_j)$를 계산하고, M-step에서 $\pi^T_y\leftarrow\frac1m\sum_j\hat p_T(y\mid\bx_j)$로 갱신한다. Mixture model의 weight 추정과 같은 EM이다. Source posterior가 calibrated되어 있어야 정확하다(Chapter 21).
- Black-box shift estimation(BBSE; Lipton et al., 2018): 아무 classifier $h$나 써서, source validation data에서 confusion matrix $\mathbf C_{ij}=P_S(h(\bx)=i\mid y=j)$를 추정한다. Label shift 아래에서 $P_S(h=i\mid y=j)=P_T(h=i\mid y=j)$이므로 $P_T(h=i)=\sum_j\mathbf C_{ij}\pi^T_j$, 즉 $\boldsymbol\mu_T=\mathbf C\boldsymbol\pi^T$이다. Target에서 예측 비율 $\hat{\boldsymbol\mu}_T$를 세고 $\hat{\boldsymbol\pi}^T=\hat{\mathbf C}^{-1}\hat{\boldsymbol\mu}_T$로 푼다. Classifier가 calibrated일 필요가 없고 $\mathbf C$가 invertible이기만 하면 된다.
예를 들어 $X\mid y\sim\N(\pm1,1)$, source prior 0.5, target prior 0.1인 문제에서 target의 label 없는 10,000개로 EM은 $\hat\pi^T_1=0.102$, BBSE는 $0.0996$을 얻었다. 보정 전 source posterior로 분류한 target 정확도는 0.842였고, 추정한 prior로 보정하면 0.933으로 참 prior를 아는 경우(0.933)와 같아졌다. Prior 보정은 threshold만 바꾸므로 AUC는 변하지 않지만, 정확도, PPV(Chapter 22), calibration은 크게 달라진다.
23.4Domain adaptation 이론과 DANN
$p(\bx\mid y)$ 자체가 바뀌는 경우(장비, 촬영 조건, 문체의 차이)에는 위의 보정이 불가능하다. Target label이 없다면 무엇을 보장할 수 있을까?
Hypothesis class $\mathcal H$의 모든 $h$에 대해 $$\varepsilon_T(h)\le\varepsilon_S(h)+\tfrac12\,d_{\mathcal H\Delta\mathcal H}(p_S,p_T)+\lambda^\ast,\qquad\lambda^\ast=\min_{h'\in\mathcal H}\big[\varepsilon_S(h')+\varepsilon_T(h')\big].$$ $d_{\mathcal H\Delta\mathcal H}$는 $\mathcal H$의 두 함수가 의견을 달리하는 영역을 이용해 두 input distribution을 얼마나 구분할 수 있는지를 재는 거리이다.
Target error는 source error, 두 domain을 classifier로 구분할 수 있는 정도, 그리고 두 domain에서 동시에 잘하는 이상적인 hypothesis의 error로 bound된다. 이로부터 "source에서 잘 맞히면서, source와 target을 구분할 수 없는 representation을 배워라"라는 설계가 나온다. DANN(domain-adversarial neural network; Ganin et al., 2016)은 feature extractor $g$ 위에 label classifier $h$와 domain classifier $c$를 두고 $$\min_{g,h}\max_c\ \L_{\text{label}}(h\circ g;\ \text{source})-\lambda\,\L_{\text{domain}}(c\circ g;\ \text{source}\cup\text{target})$$ 를 푼다. Domain classifier는 feature로 domain을 맞히려 하고, feature extractor는 그것을 속이려 한다(Chapter 16의 GAN과 같은 minimax). 구현은 backward에서 gradient의 부호만 뒤집는 gradient reversal layer 하나로 한다.
그러나 bound의 세 번째 항 $\lambda^\ast$는 data로 측정할 수 없고, representation의 marginal distribution을 맞추는 것이 오히려 $\lambda^\ast$를 키울 수 있다. 특히 label shift가 함께 있으면 $p_S(g(\bx))=p_T(g(\bx))$를 강제하는 것은 class 비율이 다른 두 distribution을 억지로 겹치게 하는 것이어서 target error의 하한이 커진다(Zhao et al., 2019). Domain adaptation 방법은 target에서 일부라도 label을 얻어 검증하기 전에는 개선을 믿어서는 안 된다.
23.5Test-time adaptation
배포 후 target input이 들어오는 대로 model을 조금 고치는 방법도 있다. 가장 단순하고 효과적인 것은 BatchNorm의 running statistics를 target data로 다시 추정하는 것이다(AdaBN; Li et al., 2018). 장비나 촬영 조건의 차이가 feature의 평균과 분산 차이로 나타나는 경우가 많아서, 학습된 weight는 두고 정규화 통계만 바꿔도 상당 부분 회복된다. Chapter 4에서 BatchNorm이 inference 때 running average를 쓴다고 했는데, 바로 그 값을 교체하는 것이다. TENT(Wang et al., 2021)는 여기에 더해 target 예측의 entropy를 최소화하도록 normalization layer의 affine parameter만 update한다(Chapter 14의 entropy minimization). 둘 다 label이 필요 없지만, entropy minimization은 틀린 예측을 확신하게 만들 위험이 있어 shift가 클수록 조심해야 한다.
23.6Shift를 감지하고 진단하기
대응하기 전에 shift가 있는지, 어떤 종류인지를 알아야 한다. 통계학의 two-sample test가 그대로 쓰인다.
- Input shift. Pre-trained network의 feature 공간에서 source와 target sample이 같은 distribution인지 검정한다. Kernel mean embedding 사이의 거리인 MMD(Gretton et al., 2012)를 쓰거나, source와 target을 구분하는 classifier를 학습해 그 held-out 정확도(또는 AUC)가 우연 수준인지 permutation test로 확인하는 classifier two-sample test(Lopez-Paz & Oquab, 2017)를 쓴다. 후자는 위의 importance weight 추정과 같은 classifier를 재사용한다. 차원 축소한 feature에서 차원별 검정을 다중비교 보정과 함께 하는 단순한 방법도 실제로 잘 작동한다(Rabanser et al., 2019).
- Label shift. 예측 class 비율의 변화나 BBSE 추정치로 감지한다.
- 성능 저하의 분해. Target에 label이 있다면, source 성능을 target의 case-mix로 reweighting한 값과 실제 target 성능을 비교한다. 둘이 비슷하면 성능 차이는 대상 집단 구성의 차이(covariate·label shift)로 설명되고, 차이가 크면 같은 유형의 input에서도 model의 동작이 달라진 것(concept shift나 $p(\bx\mid y)$의 변화)이다. 외부 검증에서 "성능이 떨어졌다"를 "왜 떨어졌는가"로 바꾸는 분석이다.
Calibration은 shift에 특히 약하다(Chapter 21). Source에서 calibrated된 model도 target에서는 과신하는 경우가 많으므로, 외부 data에서는 정확도뿐 아니라 calibration을 다시 확인하고 필요하면 소량의 target data로 temperature만 다시 맞춘다.
23.7Domain generalization과 spurious correlation
Target을 전혀 보지 못한 채 새로운 domain에서도 작동하게 하는 것이 domain generalization이다. 여러 source domain(기관, 장비)을 학습에 쓰고 domain 사이에서 변하지 않는 관계만 배우게 하려는 시도가 많다. Invariant risk minimization(IRM; Arjovsky et al., 2019)은 모든 domain에서 동시에 최적인 classifier를 갖는 representation을 찾으려 하고, group DRO(Sagawa et al., 2020)는 평균 risk 대신 최악 group의 risk $\max_g R_g(f)$를 최소화한다. 후자는 배경과 class가 상관된 data(예: 물새 사진의 배경이 대부분 물인 Waterbirds)에서 model이 배경이라는 지름길(spurious feature)에 의존하는 것을 막는 데 효과적이며, 강한 regularization과 함께 써야 한다. 그러나 여러 domain을 모은 benchmark(WILDS; Koh et al., 2021)에서 이런 방법들이 단순히 모든 data로 학습한 ERM을 일관되게 넘지 못한다는 결과도 많다. 현재 가장 확실한 domain generalization 수단은 다양한 data로 pre-training한 큰 foundation model과 강한 data augmentation이다.
23.8정리
| 상황 | 필요한 target 정보 | 방법 | 전제 |
|---|---|---|---|
| Covariate shift | Unlabeled $\bx$ | Importance weighting (domain classifier) | $p(y\mid\bx)$ 불변, support 겹침 |
| Label shift | Unlabeled $\bx$ | EM, BBSE로 prior 추정 → posterior 보정 | $p(\bx\mid y)$ 불변 |
| $p(\bx\mid y)$ 변화 | Unlabeled $\bx$ | DANN, BN 재추정, TENT | 이상적인 공통 hypothesis 존재(검증 불가) |
| Concept shift | Labeled target data | 재학습, fine-tuning, 지속적 monitoring | 없음 |
| 미지의 domain | 없음 | 다양한 pre-training, augmentation, group DRO | 학습 domain들이 변동을 대표 |
어떤 보정이든 전제가 data로 완전히 검증되지 않는다는 점을 기억해야 한다. 소량이라도 target에서 label을 얻어 보정 전후를 paired로 비교하는 것(Chapter 22)이 유일하게 확실한 검증이다.
Extensions
Chapter 24Survival Analysis와 DeepSurv
Lecture Week 08 (Survival analysis, CoxPH, DeepSurv, DeepHit)
Deep learning의 loss가 likelihood에서 나온다는 원리가 가장 깔끔하게 드러나는 예가 survival analysis이다. Event가 일어나기까지의 시간(time-to-event)을 다루는 이 분야는 censoring 때문에 일반적인 regression loss를 쓸 수 없다. 이 장에서는 survival function과 hazard function을 정의하고, Kaplan–Meier estimator와 Cox proportional hazards model을 거쳐, Cox의 partial likelihood를 loss로 쓰는 DeepSurv와 discrete-time model인 DeepHit까지 다룬다. 예시는 고객 이탈(churn)이나 기계 고장처럼 도메인을 가리지 않는 time-to-event 문제로 든다.
24.1Survival time과 기본 함수들
Survival analysis의 목적은 event가 일어날 때까지의 시간, 즉 survival time의 distribution을 추정하고 집단 간에 비교하는 것이다. Event는 고장, 이탈, 사망 등 무엇이든 될 수 있다. 예를 들어 서로 다른 요금제 A, B를 쓰는 고객 집단이 있을 때 "해지까지의 시간이 두 집단 간에 어떻게 다른가"가 전형적인 질문이다.
Survival time $T\ge0$이 pdf $f$, cdf $F(t)=P(T\le t)=\int_0^tf(u)\,\dd u$를 가진다고 하자.
(a) Survival function: $S(t)=P(T>t)=1-F(t)$.
(b) Hazard function: $h(t)=\displaystyle\lim_{\Delta t\to0}\frac{P(t\le T\lt t+\Delta t\mid T\ge t)}{\Delta t}$.
(c) Cumulative hazard: $H(t)=\int_0^th(u)\,\dd u$.
$S(t)$는 시점 $t$까지 event 없이 살아남을 확률로, $S:[0,\infty)\to[0,1]$은 $S(0)=1$에서 시작하는 non-increasing function이다. Hazard는 "시점 $t$까지 살아남았다는 조건 하에서, 바로 다음 순간 event가 일어나는 순간 발생률"이다. 확률이 아니라 rate이므로 1보다 클 수 있다.
$$h(t)=\frac{f(t)}{S(t)}=-\frac{\dd}{\dd t}\log S(t),\qquad H(t)=-\log S(t),\qquad S(t)=\exp\big(-H(t)\big).$$
$P(t\le T\lt t+\Delta t\mid T\ge t)=\frac{F(t+\Delta t)-F(t)}{S(t)}$(continuous이므로 $P(T\ge t)=S(t)$)이고, $\Delta t$로 나눠 극한을 취하면 $f(t)/S(t)$. $S'=-f$이므로 이는 $-S'(t)/S(t)=-(\log S)'(t)$. $0$부터 $t$까지 적분하면 $S(0)=1$에서 $H(t)=-\log S(t)$.
(강의 슬라이드의 hazard 유도에는 $S(t)$로 나누는 부분이 "$+S(t)$"로 잘못 적혀 있었다. 조건부 확률이므로 나눗셈이 맞다.) 예를 들어 hazard가 상수 $h(t)=\lambda$이면 $S(t)=e^{-\lambda t}$로 exponential distribution이고, 이는 "지금까지 얼마나 버텼는지와 무관하게 위험이 같다"는 memoryless 성질에 대응한다. Weibull distribution $h(t)=\lambda kt^{k-1}$은 $k>1$이면 시간이 갈수록 위험이 커지는(노화, 마모) 경우를 표현한다.
24.2Censoring
Survival data의 본질적인 어려움은 모든 대상의 event 시각을 관측하지 못한다는 것이다. 관찰 기간이 끝날 때까지 event가 일어나지 않았거나, 중간에 추적이 끊긴 대상은 "적어도 이 시점까지는 event가 없었다"는 정보만 남는다. 이를 right censoring이라 한다.
대상 $i$의 실제 event 시각을 $T_i$, censoring 시각을 $C_i$라 하면 관측되는 것은 $$Y_i=\min(T_i,C_i),\qquad\delta_i=\ind[T_i\le C_i]$$ 이다($\delta_i=1$이면 event 관측, 0이면 censored). 보통 $T_i$와 $C_i$가 covariate가 주어졌을 때 independent하다는 non-informative censoring을 가정한다. Censored 대상을 버리면 오래 버틴 대상이 체계적으로 빠져 survival을 과소추정하고, censoring 시각을 event 시각으로 취급해도 마찬가지로 bias가 생긴다. 그래서 MSE regression을 그대로 쓸 수 없다.
Censoring을 반영한 likelihood는 event가 관측된 대상은 density $f(Y_i)$로, censored 대상은 그 시점까지 살아남았을 확률 $S(Y_i)$로 기여한다. $$\L=\prod_{i=1}^nf(Y_i)^{\delta_i}S(Y_i)^{1-\delta_i}=\prod_{i=1}^nh(Y_i)^{\delta_i}S(Y_i).$$ (두 번째 등식은 $f=hS$를 쓴 것이다.)
24.3Kaplan–Meier estimator
Event가 관측된 서로 다른 시각을 $t_{(1)}\lt t_{(2)}\lt\cdots$라 하고, 각 시각 직전까지 살아남아 관찰 중인 대상의 집합을 risk set $R(t_{(j)})=\{i:Y_i\ge t_{(j)}\}$, 그 크기를 $n_j$, 그 시각에 일어난 event 수를 $d_j$라 하자.
$$\hat S(t)=\prod_{j:\,t_{(j)}\le t}\Big(1-\frac{d_j}{n_j}\Big).$$
$S(t)$를 "각 event 시각을 무사히 넘길 조건부 확률"들의 곱으로 쓰고, 각 조건부 확률을 risk set 안의 비율로 추정한 것이다. Censored 대상은 censoring 시각까지 risk set에 포함되었다가 빠지므로 정보를 버리지 않는다. 이는 censored data에 대한 nonparametric MLE이며, 분산은 Greenwood formula로 추정하고 두 집단의 곡선 비교는 log-rank test로 한다.
Kaplan–Meier는 covariate를 쓰지 않는다. 집단 몇 개를 비교하는 것은 가능하지만, 나이, 사용량, 지역처럼 covariate가 많아지고 연속형이 섞이면 집단을 나눌 수 없게 된다. Covariate의 효과를 regression처럼 추정하려면 model이 필요하다.
24.4Cox proportional hazards model
Linear regression $y=\bx^\top\bbeta+\epsilon$에 대응하는 survival model이 Cox model이다.
$$h(t\mid\bx)=h_0(t)\exp(\bx^\top\bbeta),\qquad\text{equivalently}\qquad\log\frac{h(t\mid\bx)}{h_0(t)}=\bx^\top\bbeta,$$ 여기서 $\bx=(x_1,\dots,x_p)$는 covariate(intercept 없음), $h_0(t)$는 모든 대상이 공유하는 baseline hazard로 형태를 가정하지 않는다.
Hazard가 시간에만 의존하는 부분 $h_0(t)$와 covariate에만 의존하는 scalar $\exp(\bx^\top\bbeta)$의 곱으로 분리된다. $h_0$는 nonparametric, $\bbeta$는 parametric이므로 semi-parametric model이다. Intercept가 없는 이유는 $\exp(\beta_0)$가 $h_0(t)$에 흡수되어 identifiable하지 않기 때문이다.
두 대상 $\bx_1,\bx_2$의 hazard 비는 $$\frac{h(t\mid\bx_1)}{h(t\mid\bx_2)}=\exp\big((\bx_1-\bx_2)^\top\bbeta\big)$$ 로 시간 $t$와 무관한 상수이다. 이것이 proportional hazards(PH) 가정이다. 그래서 $\exp(\beta_j)$는 다른 covariate를 고정했을 때 $x_j$가 1 증가하면 hazard가 몇 배가 되는지, 즉 hazard ratio(HR)이다. Survival function으로 쓰면 $S(t\mid\bx)=S_0(t)^{\exp(\bx^\top\bbeta)}$로, 모든 대상의 survival curve가 같은 baseline curve의 거듭제곱이 된다. 서로 다른 covariate 조합(예: "젊은 장기 약정 고객"과 "단기 약정 고객")의 곡선은 같은 모양을 공유하고, scalar $\exp(\bx^\top\bbeta)$만큼 더 빨리 혹은 느리게 떨어진다.
고객 이탈 data에 Cox model을 적합해 $\log\frac{h(t\mid\bx)}{h_0(t)}=-0.03\cdot(\text{월 사용시간})+0.29\cdot(\text{단기 약정})+0.00\cdot(\text{가입 경로})$를 얻었다고 하자(가상의 수치). 월 사용시간의 HR은 $e^{-0.03}\approx0.97$로, 사용시간이 1시간 늘 때 이탈 hazard가 약 3% 줄어든다. 즉 사용시간이 많을수록 survival curve가 천천히 떨어진다. 단기 약정의 HR은 $e^{0.29}\approx1.34$로 장기 약정 대비 hazard가 34% 높다. 계수가 0으로 추정된 가입 경로는 hazard에 영향을 주지 않는다는 뜻이다.
| Kaplan–Meier | Cox PH | |
|---|---|---|
| 추정 대상 | $S(t)$ 직접 | Hazard ratio $\exp(\bx^\top\bbeta)$ (필요하면 $h_0$도 추정해 $S(t\mid\bx)$) |
| Covariate | 사용 안 함 (집단별로 따로 추정) | 사용함, 연속형과 다수의 covariate 가능 |
| 가정 | Nonparametric | Proportional hazards, log-linear effect |
24.5Partial likelihood
$h_0(t)$를 모르는 상태에서 $\bbeta$를 어떻게 추정할까? Cox의 아이디어는 "event가 일어난 시각에, risk set 중 바로 그 대상에게 event가 일어날 조건부 확률"만 쓰는 것이다. 시각 $Y_i$에 event가 정확히 하나 일어났다는 조건 하에서 그것이 대상 $i$일 확률은 $$\frac{h(Y_i\mid\bx_i)}{\sum_{j\in R(Y_i)}h(Y_i\mid\bx_j)}=\frac{h_0(Y_i)\exp(\bx_i^\top\bbeta)}{\sum_{j\in R(Y_i)}h_0(Y_i)\exp(\bx_j^\top\bbeta)}=\frac{\exp(\bx_i^\top\bbeta)}{\sum_{j\in R(Y_i)}\exp(\bx_j^\top\bbeta)}$$ 이다. $h_0(Y_i)$가 약분되어 사라진다.
$$\mathrm{PL}(\bbeta)=\prod_{i:\,\delta_i=1}\frac{\exp(\bx_i^\top\bbeta)}{\sum_{j\in R(Y_i)}\exp(\bx_j^\top\bbeta)},\qquad R(t)=\{j:Y_j\ge t\}.$$ Counting process notation으로는 at-risk indicator $Y_i(t)$와 event counting process $N_i(t)$를 써서 $\prod_i\prod_{t\ge0}\Big(\frac{Y_i(t)\exp(\bx_i^\top\bbeta)}{\sum_jY_j(t)\exp(\bx_j^\top\bbeta)}\Big)^{\dd N_i(t)}$로 쓴다.
Event가 관측된 대상의 event 시각만 곱에 들어가지만, censored 대상도 censoring 전까지 분모의 risk set에 들어가 정보를 준다. Partial likelihood는 완전한 likelihood가 아니지만, 이를 maximize한 추정량은 consistent하고 asymptotically normal하며 그 분산은 partial likelihood의 information matrix로 추정된다. 같은 시각에 event가 여럿이면(ties) Breslow나 Efron approximation을 쓴다.
$\ell(\bbeta)=\log\mathrm{PL}(\bbeta)=\sum_{i:\delta_i=1}\Big[\bx_i^\top\bbeta-\log\sum_{j\in R(Y_i)}e^{\bx_j^\top\bbeta}\Big]$에 대해, $w_{ij}=e^{\bx_j^\top\bbeta}/\sum_{k\in R(Y_i)}e^{\bx_k^\top\bbeta}$라 하면 $$\nabla\ell(\bbeta)=\sum_{i:\delta_i=1}\big(\bx_i-\bar\bx_i\big),\qquad\nabla^2\ell(\bbeta)=-\sum_{i:\delta_i=1}\sum_{j\in R(Y_i)}w_{ij}(\bx_j-\bar\bx_i)(\bx_j-\bar\bx_i)^\top\preceq0,$$ 여기서 $\bar\bx_i=\sum_{j\in R(Y_i)}w_{ij}\bx_j$이다. 따라서 $\ell$은 concave이다.
$\log\sum_je^{\bx_j^\top\bbeta}$는 log-sum-exp 함수이며, gradient는 softmax 가중 평균 $\bar\bx_i$, Hessian은 그 가중치 하의 covariance matrix이다(Chapter 3의 softmax 미분과 같은 계산). Covariance는 positive semidefinite이므로 부호를 바꾸면 negative semidefinite이다.
Gradient $\sum(\bx_i-\bar\bx_i)$는 "event가 일어난 대상의 covariate와 risk set의 가중 평균 covariate의 차이"이며, logistic regression의 score equation과 같은 구조이다. 실제로 $\ell$의 각 항은 risk set 안에서의 softmax cross-entropy이다. Concave이므로 maximum은 global이고, Newton–Raphson $$\hat\bbeta^{(n+1)}=\hat\bbeta^{(n)}-\big[\nabla^2\ell(\hat\bbeta^{(n)})\big]^{-1}\nabla\ell(\hat\bbeta^{(n)})=\hat\bbeta^{(n)}+\mathcal I(\hat\bbeta^{(n)})^{-1}U(\hat\bbeta^{(n)})$$ 으로 빠르게 수렴한다. $U=\nabla\ell$은 score, $\mathcal I=-\nabla^2\ell$은 observed information이며 $\mathcal I(\hat\bbeta)^{-1}$이 $\hat\bbeta$의 covariance 추정치가 된다. (강의 슬라이드는 "convex(second derivative $\lt0$) → minimum"이라고 적었는데, second derivative가 음수이면 concave이고 우리가 찾는 것은 maximum이다. Negative log partial likelihood를 loss로 보면 convex이고 그 minimum을 찾는 것과 같다.)
Software(예: Python의 lifelines, R의 survival)는 계수와 HR, standard error, Wald test 외에 model 전체에 대한 지표도 출력한다. Concordance(아래의 C-index), partial AIC $=-2\ell(\hat\bbeta)+2p$, 그리고 모든 계수가 0이라는 귀무가설에 대한 log-likelihood ratio test $2\{\ell(\hat\bbeta)-\ell(\mathbf 0)\}\sim\chi^2_p$이다.
$\hat\bbeta$를 얻은 뒤 baseline cumulative hazard는 Breslow estimator $\hat H_0(t)=\sum_{i:\,Y_i\le t,\ \delta_i=1}\Big(\sum_{j\in R(Y_i)}e^{\bx_j^\top\hat\bbeta}\Big)^{-1}$로 추정하고, $\hat S(t\mid\bx)=\exp\big(-\hat H_0(t)e^{\bx^\top\hat\bbeta}\big)$로 개별 survival curve를 얻는다.
24.6Concordance index
Survival model의 예측 성능은 보통 concordance index(Harrell's C-index)로 잰다. 비교 가능한 쌍 $(i,j)$는 $Y_i\lt Y_j$이고 $\delta_i=1$인 쌍(먼저 event가 일어난 쪽이 관측된 경우)이다. Model이 준 risk score $r_i$에 대해 $$C=\frac{\sum_{(i,j)\ \text{comparable}}\Big(\ind[r_i>r_j]+\frac12\ind[r_i=r_j]\Big)}{\#\{\text{comparable pairs}\}}.$$ 먼저 event를 겪은 대상에게 더 높은 risk를 준 비율이며, 0.5는 random, 1은 완벽한 순위이다. Censoring이 없는 binary outcome에서는 ROC AUC와 같다. Cox model과 DeepSurv는 hazard의 순위를 학습하므로 C-index가 자연스러운 지표이다.
24.7DeepSurv
Cox model의 linear predictor $\bx^\top\bbeta$는 covariate 간 non-linear 관계와 interaction을 표현하지 못한다. DeepSurv(Katzman et al., 2018)는 이를 neural network로 바꾼다.
$$h(t\mid\bx)=h_0(t)\exp\big(g_\theta(\bx)\big),$$ $g_\theta:\R^p\to\R$는 scalar log-risk를 출력하는 network이다. Loss는 negative log partial likelihood $$\L(\theta)=-\frac{1}{N_E}\sum_{i:\,\delta_i=1}\Big[g_\theta(\bx_i)-\log\sum_{j\in R(Y_i)}\exp\big(g_\theta(\bx_j)\big)\Big],$$ 여기서 $N_E$는 event가 관측된 대상의 수이다. 원 논문은 여기에 weight decay 항 $\lambda\|\theta\|_2^2$를 더한다.
| Cox PH | DeepSurv | |
|---|---|---|
| Log-risk | $\bx^\top\bbeta$ (linear) | $g_\theta(\bx)$ (deep network, non-linear) |
| Objective | Partial likelihood | Negative log partial likelihood = loss function |
| Optimization | Newton–Raphson, concave이므로 global maximum | (Stochastic) gradient descent, non-convex이므로 local minimum |
| 해석 | $\exp(\beta_j)$ = HR | 직접 해석 불가 (Chapter 13의 attribution 방법 필요) |
Model이 출력하는 것은 hazard ratio의 log이다. $g_\theta$에 상수를 더해도 loss가 변하지 않으므로(softmax처럼 shift invariant) 마지막 layer의 bias는 의미가 없다. Proportional hazards 가정은 그대로 남는다. $g_\theta(\bx)$가 시간과 무관하기 때문이다.
Mini-batch 문제
Partial likelihood의 분모는 risk set 전체에 대한 합이다. Mini-batch로 학습하면 risk set을 batch 안의 대상으로 제한하게 되어 loss의 unbiased estimate가 아니다(log 안의 합이 바뀌므로). Batch가 작을수록 risk set의 근사가 나빠지므로 가능한 한 큰 batch를 쓰거나, data가 작으면 full batch로 학습한다. 구현은 batch를 $Y$의 내림차순으로 정렬하면 각 대상의 risk set이 "앞쪽 전체"가 되므로, 분모를 cumulative log-sum-exp 한 번으로 $O(B)$에 계산할 수 있다.
학습이 잘 되면 training loss가 줄고 validation C-index가 증가하며, 이를 통해 overfitting 여부를 확인한다.
원 논문은 Cox PH(CPH), random survival forest(RSF)와 C-index를 비교했다. Hazard가 covariate의 linear function인 simulated data에서는 CPH(0.779)와 DeepSurv(0.778)가 같았지만, non-linear simulated data에서는 CPH가 0.487로 random 수준이고 DeepSurv는 0.652, RSF는 0.627이었다. 실제 data에서는 dataset에 따라 DeepSurv나 RSF가 가장 좋았다. 진짜 관계가 linear이면 Cox model로 충분하고, non-linear 관계와 interaction이 있을 때 flexible model이 이득을 본다는, 통계학에서 익숙한 결론이다.
24.8DeepHit
DeepSurv는 PH 가정을 유지하고 hazard ratio를 추정하며, 결과적으로 survival time의 순서를 model한다. DeepHit(Lee et al., 2018)는 PH 가정 없이 event 발생 시각 자체의 distribution을 직접 예측한다. 시간을 grid $\{t_1,\dots,t_S\}$로 이산화하고, event 종류가 $K$가지인 competing risks(먼저 일어난 event가 다른 event의 관측을 막는 상황) 설정에서, network가 joint pmf $$P(T=t_s,\ \text{event}=k\mid\bx),\qquad s=1,\dots,S,\ k=1,\dots,K$$ 를 softmax output으로 낸다. Loss는 (a) censoring을 반영한 log-likelihood — event가 관측된 대상은 $\log P(T=Y_i,\text{event}=k_i\mid\bx_i)$, censored 대상은 $\log\big(1-\sum_kF_k(Y_i\mid\bx_i)\big)$ — 와 (b) 먼저 event가 난 대상의 cumulative incidence가 더 크도록 하는 ranking loss의 합이다. Competing risks를 다룬다는 점에서 통계학의 Fine–Gray model과 같은 역할을 한다.
Chapter 25Reinforcement Learning: Policy Gradient에서 GRPO까지
새로 추가한 장 (강의 범위 밖). Williams 1992; Sutton et al. 2000; Schulman et al. 2015, 2016, 2017; Shao et al. 2024; Ahmadian et al. 2024
지금까지의 학습은 정답 $y$가 주어진 supervised learning이거나, data의 distribution을 배우는 generative modeling이었다. Reinforcement learning(RL)에서는 정답이 없고, model(agent)이 직접 행동한 결과로 받는 reward만 있다. 학습 data가 model 자신의 행동으로 만들어진다는 점이 핵심적인 차이이다. 이 장은 다음 장의 RLHF와 최근 reasoning model 학습(RL with verifiable rewards)에 필요한 RL을 통계학의 관점에서 정리한다. Policy gradient는 score function estimator이고, baseline은 control variate이며, PPO는 importance sampling을 안전하게 쓰는 방법이다.
25.1Markov decision process
MDP는 state 공간 $\mathcal S$, action 공간 $\mathcal A$, transition $P(s'\mid s,a)$, reward $r(s,a)$, 초기 분포 $\rho_0$, discount factor $\gamma\in[0,1]$로 이루어진다. Policy $\pi_\theta(a\mid s)$는 state에서 action의 distribution이다. Trajectory $\tau=(s_0,a_0,r_0,s_1,a_1,r_1,\dots,s_T)$의 확률은 $$p_\theta(\tau)=\rho_0(s_0)\prod_{t=0}^{T-1}\pi_\theta(a_t\mid s_t)\,P(s_{t+1}\mid s_t,a_t)$$ 이고, 목표는 기대 누적 reward $J(\theta)=\E_{\tau\sim p_\theta}\big[\sum_{t=0}^{T-1}\gamma^tr_t\big]$의 최대화이다.
Policy $\pi$ 아래에서 state의 가치 $V^\pi(s)=\E_\pi[\sum_{k\ge0}\gamma^kr_{t+k}\mid s_t=s]$, state–action의 가치 $Q^\pi(s,a)=\E_\pi[\sum_{k\ge0}\gamma^kr_{t+k}\mid s_t=s,a_t=a]$, 그리고 그 차이인 advantage $A^\pi(s,a)=Q^\pi(s,a)-V^\pi(s)$를 정의한다. Advantage는 "이 state에서 평균적인 행동보다 이 행동이 얼마나 나은가"이다. 정의에서 바로 Bellman equation $Q^\pi(s,a)=r(s,a)+\gamma\E_{s'\sim P(\cdot\mid s,a)}[V^\pi(s')]$, $V^\pi(s)=\E_{a\sim\pi}[Q^\pi(s,a)]$가 나온다.
Language model을 MDP로 보기. Prompt $x$와 지금까지 생성한 token $y_{\lt t}$가 state, 다음 token $y_t$가 action, policy는 language model $\pi_\theta(y_t\mid x,y_{\lt t})$ 자체이다. Transition은 token을 이어 붙이는 deterministic 연산이고, reward는 보통 답변이 끝났을 때 한 번(reward model 점수나 정답 여부) 주어진다. $\gamma=1$로 둔다.
25.2Policy gradient theorem
Reward는 환경이 주는 것이므로 $\theta$에 대해 미분할 수 없고, transition $P$도 모른다. 그런데도 $J$의 gradient는 sample로 추정할 수 있다.
Reward-to-go $G_t=\sum_{t'=t}^{T-1}\gamma^{t'-t}r_{t'}$와 state만의 함수인 임의의 baseline $b(s_t)$에 대해 $$\nabla_\theta J(\theta)=\E_{\tau\sim p_\theta}\Big[\sum_{t=0}^{T-1}\gamma^t\,\nabla_\theta\log\pi_\theta(a_t\mid s_t)\,\big(G_t-b(s_t)\big)\Big]=\E_{\tau\sim p_\theta}\Big[\sum_{t=0}^{T-1}\gamma^t\,\nabla_\theta\log\pi_\theta(a_t\mid s_t)\,A^{\pi_\theta}(s_t,a_t)\Big].$$
1단계 (log-derivative trick). $R(\tau)=\sum_t\gamma^tr_t$라 하면 $\nabla J=\int\nabla p_\theta(\tau)R(\tau)\,\dd\tau=\E[\nabla\log p_\theta(\tau)\,R(\tau)]$이다. $\log p_\theta(\tau)$에서 $\rho_0$와 $P$는 $\theta$와 무관하므로 $\nabla\log p_\theta(\tau)=\sum_t\nabla\log\pi_\theta(a_t\mid s_t)$. 환경 model 없이 policy의 score만으로 충분하다.
2단계 (causality). 핵심 사실은 $\E_{a\sim\pi_\theta(\cdot\mid s)}[\nabla\log\pi_\theta(a\mid s)]=\sum_a\nabla\pi_\theta(a\mid s)=\nabla1=\mathbf 0$이다. $t'\lt t$이면 $r_{t'}$은 $(s_0,a_0,\dots,s_t)$까지로 정해지므로, 그것을 조건으로 $a_t$에 대해 먼저 기댓값을 취하면 $\E[\nabla\log\pi(a_t\mid s_t)\,r_{t'}]=0$이다. 따라서 $R(\tau)$ 중 $t$ 이후의 reward $\gamma^tG_t$만 남는다. 같은 논리로 $\E[\nabla\log\pi(a_t\mid s_t)b(s_t)]=0$이므로 baseline을 빼도 기댓값이 같다.
3단계. $(s_t,a_t)$를 조건으로 $G_t$의 기댓값은 $Q^\pi(s_t,a_t)$이고(tower property), $b=V^\pi$로 두면 advantage 형태가 된다.
이것은 Chapter 15에서 VAE의 대안으로 언급한 score function estimator(REINFORCE)와 같은 것이다. Sample 하나로 만든 추정량 $\hat\bg=\sum_t\nabla\log\pi(a_t\mid s_t)(G_t-b)$는 unbiased이지만 분산이 크다. 실제 구현에서는 $\gamma^t$ 인자를 생략하는 경우가 많은데, 엄밀히는 이 경우 다른 목적함수의 gradient가 되지만 실용적으로 잘 작동한다.
25.3Baseline은 control variate이다
Baseline은 기댓값을 바꾸지 않으면서 분산을 줄이는 통계학의 control variate이다. $\mathbf s=\nabla\log\pi(a\mid s)$, return $G$라 할 때, 한 좌표에 대해 $\Var(s(G-b))=\E[s^2(G-b)^2]-(\E[sG])^2$를 $b$에 대해 최소화하면 $$b^\ast=\frac{\E[s^2G]}{\E[s^2]}$$ 으로, score의 크기로 가중한 return의 평균이다. 보통은 그 근사로 $V^\pi(s)$를 쓴다. 효과는 극적이다. Reward에 상수 5가 더해진 5-armed bandit에서 softmax policy의 gradient를 batch 8개로 추정하면, 추정량 분산의 합이 baseline 없이 3.12, 정확한 $V$를 baseline으로 쓰면 0.106으로 약 30배 준다(20,000번 반복한 simulation). Reward에 상수를 더해도 gradient의 기댓값은 그대로인데, baseline이 없으면 그 상수가 분산을 키운다.
Actor–critic과 GAE
$V^\pi$를 모르므로 network $V_\phi(s)$(critic)를 return에 대한 regression으로 함께 학습한다. Policy는 actor라 부른다. Critic이 있으면 한 step만 보고 advantage를 추정할 수 있다. TD error $$\delta_t=r_t+\gamma V(s_{t+1})-V(s_t)$$ 는 $V=V^\pi$이면 $\E[\delta_t\mid s_t,a_t]=r_t+\gamma\E[V^\pi(s_{t+1})\mid s_t,a_t]-V^\pi(s_t)=Q^\pi(s_t,a_t)-V^\pi(s_t)=A^\pi(s_t,a_t)$로 advantage의 unbiased estimate이다. $V$가 부정확하면 bias가 생기지만 분산은 return 전체를 쓰는 것보다 훨씬 작다. Generalized advantage estimation(GAE; Schulman et al., 2016)은 그 사이를 $\lambda\in[0,1]$로 잇는다. $$\hat A_t^{\text{GAE}(\gamma,\lambda)}=\sum_{l=0}^{T-t-1}(\gamma\lambda)^l\,\delta_{t+l}.$$ $\lambda=0$이면 $\delta_t$(낮은 분산, critic의 오차만큼 bias), $\lambda=1$이면 $\sum_l\gamma^l\delta_{t+l}$이 telescoping되어 $G_t-V(s_t)$(Monte Carlo, unbiased, 높은 분산)이다($V(s_T)=0$). Ridge의 $\lambda$처럼 bias–variance trade-off를 조절하는 parameter이며, 보통 $\lambda=0.95$ 근처를 쓴다.
25.4Importance sampling과 trust region
Policy gradient는 현재 policy로 sample을 새로 모아야 한다(on-policy). Sample 수집이 비싸므로 한 번 모은 data로 여러 번 update하고 싶은데, update 후에는 data를 만든 policy $\pi_{\text{old}}$와 학습 중인 $\pi_\theta$가 달라진다. 다음 lemma가 출발점이다.
임의의 두 policy $\pi,\pi'$에 대해 $$J(\pi')-J(\pi)=\E_{\tau\sim\pi'}\Big[\sum_t\gamma^tA^\pi(s_t,a_t)\Big].$$
$A^\pi(s_t,a_t)=\E\big[r_t+\gamma V^\pi(s_{t+1})-V^\pi(s_t)\mid s_t,a_t\big]$이므로 $\pi'$의 trajectory를 따라 더하면 $\sum_t\gamma^t(r_t+\gamma V^\pi(s_{t+1})-V^\pi(s_t))=\sum_t\gamma^tr_t-V^\pi(s_0)$이 telescoping된다. 기댓값을 취하면 $J(\pi')-\E_{s_0\sim\rho_0}V^\pi(s_0)=J(\pi')-J(\pi)$.
우변은 새 policy $\pi'$가 방문하는 state에서의 기댓값이라 계산할 수 없다. State 분포를 기존 policy의 것으로 바꾸고 action만 importance weight로 보정한 surrogate objective $$L_{\pi_{\text{old}}}(\pi_\theta)=\E_{\tau\sim\pi_{\text{old}}}\Big[\sum_t\rho_t(\theta)\,\hat A_t\Big],\qquad\rho_t(\theta)=\frac{\pi_\theta(a_t\mid s_t)}{\pi_{\text{old}}(a_t\mid s_t)}$$ 는 $\theta=\theta_{\text{old}}$에서 값과 gradient가 모두 $J$와 일치한다($\nabla\rho_t|_{\theta_{\text{old}}}=\nabla\log\pi_\theta(a_t\mid s_t)|_{\theta_{\text{old}}}$이므로 policy gradient theorem의 식이 된다). 즉 1차 근사로서 정확하며, 두 policy가 가까울 때만 믿을 수 있다. TRPO(Schulman et al., 2015)는 $J(\pi')$와 surrogate의 차이가 두 policy 사이의 최대 KL divergence로 bound된다는 결과에 근거해 KL constraint $\E[\KL(\pi_{\text{old}}\|\pi_\theta)]\le\delta$ 아래에서 surrogate를 최대화한다. 2차 최적화가 필요해 구현이 복잡하다.
PPO
PPO(proximal policy optimization; Schulman et al., 2017)는 constraint 대신 ratio를 잘라 내는(clip) 1차 방법이다. $$\L^{\text{CLIP}}(\theta)=\E_t\Big[\min\big(\rho_t(\theta)\hat A_t,\ \mathrm{clip}(\rho_t(\theta),1-\epsilon,1+\epsilon)\,\hat A_t\big)\Big].$$ $\hat A_t>0$이면 $\rho_t$가 $1+\epsilon$을 넘어도 objective가 늘지 않으므로 그 action의 확률을 지나치게 올릴 유인이 없다. $\hat A_t\lt0$이면 $1-\epsilon$ 아래로 확률을 내려도 이득이 없다. $\min$을 취하므로 clip이 objective를 키우는 방향으로는 작동하지 않는다. 즉 $\L^{\text{CLIP}}$는 clip 없는 surrogate의 pessimistic한 lower bound이다. 같은 batch로 여러 epoch를 update해도 policy가 $\pi_{\text{old}}$에서 크게 벗어나지 않는다. 실제 loss는 critic의 MSE와 탐색을 위한 entropy bonus를 더한 것이다.
25.5Language model을 위한 policy gradient
RLHF(Chapter 26)는 PPO를 language model에 적용한다. Reward는 답변 끝에 받는 reward model 점수 $r_\phi(x,y)$와 token마다의 KL penalty $-\beta\log\frac{\pi_\theta(y_t\mid x,y_{\lt t})}{\pi_{\text{ref}}(y_t\mid x,y_{\lt t})}$의 합이다. Token별 log-ratio의 합의 기댓값은 KL divergence의 chain rule에 의해 sequence 수준의 $\KL(\pi_\theta(\cdot\mid x)\|\pi_{\text{ref}}(\cdot\mid x))$와 같다. 문제는 critic이다. Policy와 같은 크기의 value network를 따로 학습해야 해서 memory가 두 배로 들고, 답변 끝에만 reward가 있으므로 token별 value를 학습하기도 어렵다. 그래서 critic 없이 같은 prompt에 대한 여러 sample로 baseline을 만드는 방법이 쓰인다.
Prompt $x$에 대해 답변 $y_1,\dots,y_G\sim\pi_{\text{old}}(\cdot\mid x)$를 뽑고 reward $r_1,\dots,r_G$를 얻는다.
RLOO(REINFORCE leave-one-out; Ahmadian et al., 2024): $\hat A_i=r_i-\frac1{G-1}\sum_{j\ne i}r_j$.
GRPO(group relative policy optimization; Shao et al., 2024): $\hat A_i=\dfrac{r_i-\mathrm{mean}(r_{1:G})}{\mathrm{std}(r_{1:G})}$를 답변 $y_i$의 모든 token에 쓰고, PPO의 clipped objective에 KL penalty를 더해
$$\frac1G\sum_{i=1}^G\frac1{|y_i|}\sum_{t=1}^{|y_i|}\min\big(\rho_{i,t}\hat A_i,\ \mathrm{clip}(\rho_{i,t},1-\epsilon,1+\epsilon)\hat A_i\big)-\beta\,\widehat{\KL}\big(\pi_\theta\|\pi_{\text{ref}}\big)$$
를 최대화한다.
(a) RLOO의 baseline은 $y_i$와 독립이므로 policy gradient 추정량이 unbiased이다.
(b) 자기 자신을 포함한 평균을 빼면 $r_i-\bar r=\frac{G-1}{G}\big(r_i-\frac1{G-1}\sum_{j\ne i}r_j\big)$이므로, RLOO 추정량에 상수 $\frac{G-1}{G}$를 곱한 것이다. 방향은 같고 크기만 줄어든다.
(c) GRPO가 쓰는 KL estimator $k_3=\frac{\pi_{\text{ref}}}{\pi_\theta}-\log\frac{\pi_{\text{ref}}}{\pi_\theta}-1$ (token마다, $y_t\sim\pi_\theta$)은 항상 0 이상이고 $\KL(\pi_\theta\|\pi_{\text{ref}})$의 unbiased estimate이다.
(a) $y_j$ ($j\ne i$)는 $y_i$와 독립이므로 $\E[\nabla\log\pi(y_i)\,b_i]=\E[\nabla\log\pi(y_i)]\E[b_i]=0$. (b) $\bar r=\frac1G r_i+\frac{G-1}{G}\cdot\frac1{G-1}\sum_{j\ne i}r_j$를 대입해 정리하면 된다. (c) $u=\pi_{\text{ref}}/\pi_\theta$라 하면 $u-\log u-1\ge0$($\log u\le u-1$). $\E_{\pi_\theta}[u]=\sum_y\pi_{\text{ref}}(y)=1$이므로 $\E[k_3]=\E_{\pi_\theta}[-\log u]=\KL(\pi_\theta\|\pi_{\text{ref}})$.
앞 절의 bandit simulation에서 RLOO는 분산 0.122로 정확한 $V$를 쓴 경우(0.106)에 근접했고, 자기 자신을 포함한 평균은 기대 gradient가 정확히 $7/8$배로 줄어든 것이 확인되었다. GRPO의 standard deviation 정규화는 group마다 다른 상수로 나누므로 엄밀히는 bias가 있고, 모든 답이 맞거나 모두 틀린 쉬운·어려운 prompt(reward 분산이 작은 group)의 비중을 키운다. 또 $1/|y_i|$ 정규화는 틀린 답변이 길수록 token당 벌이 작아져 길이를 늘리는 쪽으로 편향을 만든다는 지적이 있어(Liu et al., 2025, Dr. GRPO), 두 정규화를 뺀 변형도 쓰인다. 이런 세부 선택이 학습된 model의 답변 길이와 성능에 실제로 영향을 준다.
Verifiable reward와 reasoning model
수학 문제의 최종 답, code의 unit test처럼 정답 여부를 자동으로 판정할 수 있는 task에서는 학습된 reward model 대신 규칙 기반 verifier의 0/1 reward를 쓸 수 있다(RL with verifiable rewards, RLVR). Reward model의 허점을 파고드는 reward hacking이 크게 줄어든다(형식을 악용하는 문제는 남는다). DeepSeek-R1-Zero(DeepSeek-AI, 2025)는 pre-trained base model에 supervised fine-tuning 없이 정답 reward와 형식 reward만으로 GRPO를 적용했는데, 학습이 진행되며 답변이 길어지고 스스로 검산하고 되돌아가는 긴 chain-of-thought가 나타났다. 이후 공개된 reasoning model의 상당수가 이 방식(소량의 SFT + 대규모 RLVR)을 따른다. 통계적으로 보면 정답 여부라는 Bernoulli reward 아래에서 정답 확률 $P_\theta(\text{correct}\mid x)$를 policy gradient로 직접 올리는 것이다. 모든 sample이 틀리는 어려운 문제에서는 group 내 reward 분산이 0이라 gradient가 없으므로, 문제 난이도를 model 수준에 맞추는 curriculum이 중요하다.
25.6Value-based method
Policy를 직접 parameterize하지 않고 최적 action value를 학습하는 계열도 있다. 최적 $Q^\ast$는 Bellman optimality equation $Q^\ast(s,a)=r(s,a)+\gamma\E_{s'}[\max_{a'}Q^\ast(s',a')]$를 만족한다.
$(\mathcal TQ)(s,a)=r(s,a)+\gamma\E_{s'\sim P(\cdot\mid s,a)}[\max_{a'}Q(s',a')]$은 sup norm에서 $\gamma$-contraction이다: $\|\mathcal TQ_1-\mathcal TQ_2\|_\infty\le\gamma\|Q_1-Q_2\|_\infty$. 따라서 $\gamma\lt1$이면 고정점 $Q^\ast$가 유일하고 반복 $Q_{k+1}=\mathcal TQ_k$는 $Q^\ast$로 기하급수적으로 수렴한다.
$|\max_{a'}Q_1(s',a')-\max_{a'}Q_2(s',a')|\le\max_{a'}|Q_1(s',a')-Q_2(s',a')|\le\|Q_1-Q_2\|_\infty$이고 기댓값과 $\gamma$를 곱하면 된다. 나머지는 Banach fixed-point theorem이다.
Q-learning은 이 반복을 sample로 근사한다: $Q(s,a)\leftarrow Q(s,a)+\alpha\big[r+\gamma\max_{a'}Q(s',a')-Q(s,a)\big]$. DQN(Mnih et al., 2015)은 $Q$를 CNN으로 근사하고, 과거 경험을 저장해 무작위로 다시 뽑는 experience replay와 천천히 update되는 target network(BYOL·DINO의 EMA teacher와 같은 발상)로 학습을 안정시켜 Atari 게임에서 사람 수준의 성능을 냈다. Action이 이산적이고 적을 때 강력하지만, action 공간이 vocabulary 크기의 sequence인 language model에는 policy gradient 계열이 주로 쓰인다.
정리하면, RL에서의 통계적 과제는 세 가지이다. Reward의 기댓값을 sample로 미분하는 것(score function estimator), 그 추정량의 분산을 줄이는 것(baseline, critic, group 평균), 그리고 data를 만든 분포와 학습하는 분포가 다를 때 보정하는 것(importance sampling, clipping, KL penalty)이다.
Chapter 26Large Language Model
Lecture Week 14 (GPT, ChatGPT, RLHF)
GPT(generative pre-trained transformer)는 Chapter 8의 Transformer decoder를 거대한 text corpus 위에서 "다음 token 맞히기"로 학습한 model이다. 이 단순한 objective가 규모를 키우자 번역, 요약, 코딩, 추론까지 하는 model로 이어졌다. 이 장에서는 autoregressive language modeling을 likelihood 관점에서 정리하고, scaling law, 그리고 GPT를 ChatGPT로 바꾼 instruction tuning과 RLHF(reward model, PPO), 그 대안인 DPO를 유도한다.
26.1Autoregressive language modeling
Token sequence $\bx=(x_1,\dots,x_n)$의 distribution을 chain rule로 분해한다. $$p_\theta(\bx)=\prod_{t=1}^np_\theta(x_t\mid x_{\lt t}).$$ 이 분해는 어떤 distribution에 대해서도 성립하므로 가정이 아니다. Model이 할 일은 각 조건부 분포 $p_\theta(\cdot\mid x_{\lt t})$를 $|\mathcal V|$개 token 위의 categorical distribution으로 출력하는 것이다. GPT는 causal mask(Chapter 8)를 쓰는 Transformer decoder만으로 이를 구현한다. 위치 $t$의 output이 $x_1,\dots,x_t$만 보고 $x_{t+1}$의 distribution을 예측하므로, sequence 하나로 $n$개의 예측 문제를 한 번의 forward pass에 병렬로 학습한다.
Loss는 next-token cross-entropy, 즉 negative log-likelihood이다. $$\L(\theta)=-\frac{1}{n}\sum_{t=1}^n\log p_\theta(x_t\mid x_{\lt t}).$$ Chapter 3에서 본 대로 이는 $\KL(\hat p_{\text{data}}\|p_\theta)$의 최소화, 곧 MLE이다. Language model의 성능은 흔히 perplexity $\mathrm{PPL}=\exp(\L)$로 보고한다. PPL이 $k$라는 것은 model이 매 token마다 평균적으로 $k$개의 후보 중에서 균등하게 고르는 정도의 불확실성을 가진다는 뜻이다.
Text는 먼저 subword 단위로 tokenize된다. Byte-pair encoding(BPE)은 문자(또는 byte)에서 시작해 corpus에서 가장 자주 붙어 나오는 쌍을 반복해서 합쳐 vocabulary를 만든다. 자주 나오는 단어는 token 하나, 드문 단어는 여러 조각으로 표현되므로 vocabulary 밖의 단어(OOV)가 없다.
26.2GPT 계열의 발전
| Model | 연도 | Parameters | 핵심 변화 |
|---|---|---|---|
| GPT-1 | 2018 | 117M | Unlabeled text로 pre-training 후 task별 supervised fine-tuning |
| GPT-2 | 2019 | 1.5B | Fine-tuning 없이 prompt만으로 여러 task 수행(zero-shot) |
| GPT-3 | 2020 | 175B | Prompt에 예시 몇 개를 넣으면 task를 수행하는 in-context (few-shot) learning |
| GPT-3.5 / ChatGPT | 2022 | 비공개 | Instruction tuning + RLHF로 대화형 assistant화 |
| GPT-4 | 2023 | 비공개 | Image input, 추론 능력 향상 |
| GPT-4o | 2024 | 비공개 | Text, audio, image를 하나의 model에서 처리 |
In-context learning은 weight를 전혀 update하지 않고 prompt 안의 예시만으로 새 task를 수행하는 능력이다. GPT-3 논문은 세 가지 설정을 비교했다. Zero-shot은 task 설명만("Translate English to French: cheese =>"), one-shot은 설명과 예시 하나("sea otter => loutre de mer"), few-shot은 예시 여러 개를 prompt에 넣는다. 반면 전통적인 fine-tuning은 예시마다 gradient update를 반복한다. "학습"이 gradient descent가 아니라 forward pass 안에서 일어난다는 점이 기존 machine learning과 다르다.
Scaling law
Kaplan et al.(2020)은 test loss가 parameter 수 $N$, data token 수 $D$, 계산량 $C$에 대해 power law를 따름을 관찰했다. 예를 들어 data가 충분할 때 $L(N)\approx(N_c/N)^{\alpha_N}$, $\alpha_N\approx0.076$이다. Log–log plot에서 직선이므로 작은 model의 결과로 큰 model의 성능을 예측할 수 있고, 이것이 model을 계속 키우는 근거가 되었다. 이후 Hoffmann et al.(2022, Chinchilla)은 주어진 계산량에서 loss를 최소화하려면 $N$과 $D$를 같은 비율로 늘려야 하며, 대략 parameter 하나당 20 token 정도가 compute-optimal임을 보였다. 그 전의 model들은 크기에 비해 data가 부족했던 것이다.
26.3GPT에서 ChatGPT로
Pre-trained GPT는 "인터넷 text의 다음 token"을 잘 예측할 뿐, 사용자의 지시를 따르도록 학습된 것은 아니다. 질문을 넣으면 답 대신 비슷한 질문 목록을 이어 쓸 수도 있다. InstructGPT(Ouyang et al., 2022)와 ChatGPT는 다음 단계로 이를 바꾼다.
- Pre-training: 대규모 corpus에서 next-token prediction.
- Supervised fine-tuning (instruction tuning): 사람이 작성한 (지시, 모범 답변) 쌍으로 같은 next-token loss를 써서 fine-tuning한다. 결과를 $\pi_{\text{SFT}}$라 한다.
- Reward model 학습: 같은 prompt에 대해 model이 여러 답변을 생성하고, 사람이 순위를 매긴다. 이 비교 data로 답변의 품질을 예측하는 reward model을 학습한다.
- Reinforcement learning (PPO): Reward model의 점수를 높이도록 policy(language model)를 fine-tuning한다.
- Service: Prompt 구성, 대화 memory, tool 사용(검색, code 실행 등)이 붙는다. ChatGPT가 Python 코드를 직접 실행해 결과를 확인하는 것은 model 자체가 아니라 이 service 단계의 기능이며, 중간 과정을 사용자가 확인할 수 있다는 점에서 설명 가능성에도 도움이 된다.
3–4단계를 RLHF(reinforcement learning from human feedback)라 한다. 아래에서 각 단계의 objective를 통계적으로 정리한다.
26.4Reward model: Bradley–Terry
Prompt $x$에 대한 두 답변 중 사람이 선호한 것을 $y_w$, 아닌 것을 $y_l$이라 하자. 선호 확률을 latent "점수" $r(x,y)$의 차이로 model하는 것이 paired comparison의 고전적인 Bradley–Terry model이다. $$P(y_w\succ y_l\mid x)=\frac{\exp r(x,y_w)}{\exp r(x,y_w)+\exp r(x,y_l)}=\sigma\big(r(x,y_w)-r(x,y_l)\big).$$ Reward model $r_\phi$(보통 SFT model에 scalar head를 단 것)는 이 model의 MLE로 학습한다. $$\L_R(\phi)=-\E_{(x,y_w,y_l)}\Big[\log\sigma\big(r_\phi(x,y_w)-r_\phi(x,y_l)\big)\Big].$$ 비교 쌍을 data point로 하는 logistic regression이다. Reward는 차이만 의미가 있으므로 상수 shift에 대해 identifiable하지 않다.
26.5KL-regularized RL과 PPO
이제 language model을 policy $\pi_\theta(y\mid x)$로 보고 다음을 maximize한다. $$\max_{\pi_\theta}\;\E_{x\sim\mathcal D,\,y\sim\pi_\theta(\cdot\mid x)}\big[r_\phi(x,y)\big]-\beta\,\E_x\Big[\KL\big(\pi_\theta(\cdot\mid x)\,\|\,\pi_{\text{ref}}(\cdot\mid x)\big)\Big],\qquad\pi_{\text{ref}}=\pi_{\text{SFT}}.$$ KL penalty가 필요한 이유는 reward model이 사람 선호의 불완전한 근사이기 때문이다. Penalty가 없으면 policy가 reward model의 허점을 파고들어 점수만 높고 이상한 text를 만든다(reward hacking). $\pi_{\text{ref}}$ 근처에 머물게 하면 언어 능력을 유지하면서 선호 방향으로만 조금 이동한다.
Sampling이 미분 불가능하므로 policy gradient(Chapter 25)를 쓰며, 그중 안정적인 PPO(proximal policy optimization; Schulman et al., 2017)를 쓴다. 이전 policy $\pi_{\text{old}}$ 대비 확률비 $\rho=\pi_\theta(a\mid s)/\pi_{\text{old}}(a\mid s)$와 advantage estimate $\hat A$에 대해 $$\L^{\text{CLIP}}(\theta)=\E\Big[\min\big(\rho\hat A,\ \mathrm{clip}(\rho,1-\epsilon,1+\epsilon)\hat A\big)\Big]$$ 를 maximize한다. Clip은 한 번의 update로 policy가 너무 멀리 움직이지 않게 한다. Language model에서 state는 지금까지의 token, action은 다음 token이고, reward는 답변이 끝났을 때 $r_\phi$와 token별 KL penalty로 주어진다.
26.6DPO: reward model 없이
RLHF는 reward model 학습, sampling, PPO라는 복잡한 pipeline을 거친다. Rafailov et al.(2023)은 위 KL-regularized objective의 최적해가 closed form이라는 점을 이용해 이를 하나의 supervised loss로 바꿨다.
각 $x$에 대해 $\max_\pi\E_{y\sim\pi}[r(x,y)]-\beta\KL(\pi\|\pi_{\text{ref}})$의 해는 $$\pi^\ast(y\mid x)=\frac{1}{Z(x)}\pi_{\text{ref}}(y\mid x)\exp\Big(\frac1\beta r(x,y)\Big),\qquad Z(x)=\sum_y\pi_{\text{ref}}(y\mid x)e^{r(x,y)/\beta}.$$
Objective를 $-\beta$로 나누면 $\E_\pi\big[\log\frac{\pi(y\mid x)}{\pi_{\text{ref}}(y\mid x)}-\frac1\beta r(x,y)\big]=\E_\pi\big[\log\frac{\pi(y\mid x)}{\pi_{\text{ref}}(y\mid x)e^{r/\beta}/Z(x)}\big]-\log Z(x)=\KL(\pi\|\pi^\ast)-\log Z(x)$. $Z$는 $\pi$와 무관하므로 이를 minimize하는 것은 $\KL(\pi\|\pi^\ast)$를 minimize하는 것이고, Gibbs' inequality에 의해 $\pi=\pi^\ast$가 유일한 해이다.
이 식을 $r$에 대해 풀면 $r(x,y)=\beta\log\frac{\pi^\ast(y\mid x)}{\pi_{\text{ref}}(y\mid x)}+\beta\log Z(x)$이다. Bradley–Terry model에는 reward의 차이만 들어가므로 계산할 수 없는 $\beta\log Z(x)$가 상쇄된다. Reward를 policy로 표현해 Bradley–Terry likelihood에 대입하면 $$\L_{\text{DPO}}(\theta)=-\E_{(x,y_w,y_l)}\Big[\log\sigma\Big(\beta\log\frac{\pi_\theta(y_w\mid x)}{\pi_{\text{ref}}(y_w\mid x)}-\beta\log\frac{\pi_\theta(y_l\mid x)}{\pi_{\text{ref}}(y_l\mid x)}\Big)\Big]$$ 를 얻는다. 선호 data에 대한 logistic regression을 policy의 log-ratio로 직접 하는 셈이며, reward model과 RL 없이 같은 목표를 최적화한다(DPO, direct preference optimization).
26.7Decoding
학습된 model에서 text를 생성할 때는 매 step의 distribution $p_\theta(\cdot\mid x_{\lt t})$에서 다음 token을 고르는 규칙이 필요하다.
| Method | 규칙 | 특징 |
|---|---|---|
| Greedy | $\argmax$ token 선택 | Deterministic, 반복적이고 단조로운 text가 되기 쉬움 |
| Beam search | 누적 log-probability 상위 $k$개 sequence 유지 | 번역처럼 정답이 좁은 task에 적합 |
| Temperature | $\softmax(\mathbf z/T)$에서 sampling | $T\lt1$이면 날카롭게(보수적), $T>1$이면 평평하게(다양) |
| Top-$k$ | 확률 상위 $k$개 token으로 제한 후 재정규화 | 꼬리의 이상한 token 배제 |
| Top-$p$ (nucleus) | 누적 확률이 $p$를 넘는 최소 집합으로 제한 | Distribution 모양에 따라 후보 수가 적응적으로 변함 |
Temperature는 Chapter 12의 knowledge distillation과 같은 연산이다. $T\to0$이면 greedy, $T\to\infty$이면 uniform sampling이 된다.
Chapter 27Vision-Language Model
새로 추가한 장 (강의 범위 밖). Radford et al. 2021; Alayrac et al. 2022; Li et al. 2023; Liu et al. 2023, 2024
Chapter 12의 CLIP은 image와 text를 같은 embedding 공간에 놓아 검색과 zero-shot 분류를 가능하게 했다. 그러나 CLIP은 image에 대해 "말할" 수 없다. Vision-language model(VLM)은 image를 보고 질문에 답하고, 설명을 쓰고, 지시를 따르는 model이다. 대부분의 현대 VLM은 처음부터 새로 학습하지 않고, 이미 학습된 vision encoder와 large language model(Chapter 26)을 연결한다. 이 장은 그 연결 방식 세 가지, 학습 단계, 그리고 VLM의 대표적인 실패인 hallucination을 통계적으로 다룬다.
27.1문제 설정
VLM은 image $\mathbf v$와 text prompt $x$가 주어졌을 때 답변 $y$의 조건부 distribution을 autoregressive하게 model한다. $$p_\theta(y\mid\mathbf v,x)=\prod_tp_\theta(y_t\mid\mathbf v,x,y_{\lt t}).$$ 학습 loss는 Chapter 26과 같은 next-token cross-entropy이며, 보통 답변 token에 대해서만 계산하고 image token과 prompt token은 조건으로만 쓴다. 핵심 설계 질문은 $\mathbf v$를 language model이 읽을 수 있는 형태로 어떻게 바꾸느냐이다. Vision encoder(보통 CLIP 계열 ViT, Chapter 9)는 image를 patch token의 sequence $\bZ\in\R^{N\times d_v}$로 바꾸고, LLM은 $d$차원 token embedding의 sequence를 받는다. 둘 사이의 다리가 필요하다.
27.2세 가지 연결 방식
Projector: LLaVA
가장 단순한 방법은 각 patch feature $\bz_i$를 projector $\phi$(linear 또는 2-layer MLP)로 $d$차원으로 바꿔, text embedding sequence 앞에 그냥 이어 붙이는 것이다(LLaVA; Liu et al., 2023). LLM은 image patch를 "외국어 단어"처럼 읽는다. 학습은 두 단계이다.
- Feature alignment. Vision encoder와 LLM을 고정하고 image–caption 쌍으로 projector만 학습한다. Image token을 LLM의 단어 공간에 정렬하는 단계이다.
- Visual instruction tuning. Vision encoder만 고정하고 projector와 LLM을 함께, image에 대한 다양한 질문–답변 형식의 대화 data로 학습한다. LLaVA는 image의 caption과 bounding box 정보를 text-only LLM(GPT-4)에 주어 대화, 상세 설명, 추론 문제를 생성하게 해 이 data를 만들었다.
단순하지만 강력해서 현재 공개 VLM의 표준 구조가 되었다. 대가는 token 수이다. $336\times336$ image를 patch 14로 자르면 $24\times24=576$개의 image token이 생기고, 고해상도 image를 여러 tile로 나눠 각각 encode하면(AnyRes) 수천 개가 된다. Attention 비용(Chapter 8, 10)이 그만큼 커진다.
Learned queries: BLIP-2
Chapter 9의 Perceiver처럼, 학습되는 소수의 query가 많은 image token을 cross-attention으로 요약하게 할 수 있다. BLIP-2(Li et al., 2023)의 Q-Former는 32개의 learnable query를 가진 작은 Transformer이다. Image encoder와 LLM을 모두 고정한 채 Q-Former만 학습하며, 먼저 image–text contrastive(CLIP과 같은 InfoNCE), image–text matching(쌍이 맞는지 이진 분류), image-grounded text generation의 세 objective로 query output이 text와 관련된 visual 정보를 담도록 학습하고, 그다음 query output을 LLM 입력으로 연결해 생성 loss로 학습한다. Image가 항상 32개 token으로 압축되므로 효율적이지만, 세밀한 정보(작은 글자, 작은 물체)는 손실될 수 있다.
Cross-attention: Flamingo
Flamingo(Alayrac et al., 2022)는 image token을 LLM의 input sequence에 넣지 않는다. 고정된 LLM의 layer 사이에 새 cross-attention layer를 끼워 넣어, text token이 query로서 image feature(Perceiver resampler가 64개로 요약한 것)를 참조하게 한다. 새 layer의 output은 $\tanh(\alpha)$로 곱해 더하며 $\alpha=0$으로 초기화한다. 학습 시작 시점에는 원래 LLM과 정확히 같아서 언어 능력을 해치지 않고 시작한다는 점에서 LoRA의 $\mathbf B=\mathbf 0$ 초기화(Chapter 12)와 같은 발상이다. Image와 text가 번갈아 나오는 web 문서로 학습해, prompt에 예시 몇 개를 넣는 in-context learning(Chapter 26)이 image에서도 가능해졌다.
| Projector (LLaVA) | Learned query (BLIP-2) | Cross-attention (Flamingo) | |
|---|---|---|---|
| Image token 수 | Patch 수 (수백~수천) | 고정 (32) | LLM input에 없음 |
| 새로 학습하는 부분 | Projector (+ LLM) | Q-Former | Resampler, gated x-attn layer |
| 세밀한 정보 | 보존됨 | 압축으로 손실 가능 | 보존됨 |
| 비용 | Context 길이 증가 | 작음 | Layer 추가 |
이 셋은 모두 따로 학습된 두 model을 사후에 잇는 late fusion이다. 반대로 image를 VQ-VAE 같은 tokenizer로 이산 token으로 바꿔 처음부터 text token과 섞어 하나의 Transformer로 학습하는 early fusion(Chameleon 등) model은 image를 생성할 수도 있다. Audio도 같은 틀로 다룬다. Whisper(Radford et al., 2023)는 log-mel spectrogram을 encoder에 넣고 decoder가 text를 생성하는 encoder–decoder Transformer이며, 그 encoder를 projector로 LLM에 연결하면 음성을 이해하는 model이 된다. 생체신호나 시계열도 patch로 잘라 encoder를 학습하면 같은 방식으로 연결할 수 있다.
27.3학습 data와 fine-tuning
VLM의 품질은 구조보다 data에 크게 좌우된다. Image–caption 쌍은 web에서 대량으로 얻을 수 있지만 caption이 짧고 noisy하다. 그래서 강한 model로 상세한 caption을 다시 생성하거나(re-captioning), 문서·표·chart처럼 특정 능력에 필요한 data를 따로 모은다. 특정 domain에 적응시킬 때는 vision encoder를 고정하고 projector와 LLM의 LoRA(Chapter 29)만 학습하는 것이 일반적이다. Domain의 image 특성이 일반 사진과 크게 다르면(현미경, 의료 영상, 위성) vision encoder 자체도 그 domain data로 먼저 self-supervised pre-training(Chapter 12)하는 것이 효과적이다. Vision encoder가 보지 못한 특징은 LLM이 아무리 커도 복원할 수 없기 때문이다.
27.4Hallucination과 language prior
VLM의 가장 흔한 실패는 image에 없는 물체나 속성을 그럴듯하게 말하는 hallucination이다. 통계적으로 보면 원인은 분명하다. Model의 답변 distribution $p_\theta(y\mid\mathbf v,x)$는 image와 language prior의 결합인데, LLM은 엄청난 양의 text로 학습되어 "식탁 사진에는 포크가 있다" 같은 공기(co-occurrence) 통계를 강하게 갖고 있다. Visual evidence가 약하거나 모호하면 답은 $p(y\mid x)$, 즉 image를 보지 않은 language prior 쪽으로 끌려간다.
- 측정. Caption에 언급된 물체 중 image에 실제로 없는 비율을 세는 CHAIR(Rohrbach et al., 2018), "image에 X가 있나요?"라는 yes/no 질문을 실제 물체와 자주 함께 나오는 없는 물체에 대해 던지는 POPE(Li et al., 2023)가 쓰인다. 후자는 이진 분류 문제이므로 Chapter 22의 precision, recall, 그리고 "yes"라고 답하는 비율의 편향을 그대로 볼 수 있다.
- Blind baseline. Image를 빼거나 무관한 image를 넣고 같은 질문을 했을 때의 정확도를 반드시 함께 보고한다. Image 없이도 높은 점수가 나오는 benchmark 문제는 visual 이해가 아니라 language prior를 측정하는 것이다.
- 완화. 고해상도 input과 세밀한 grounding data(물체의 위치를 함께 말하게 하는 학습), 그리고 decoding 단계에서 원래 image로 얻은 logit과 noise를 섞은 image로 얻은 logit의 차이를 강조해 language prior의 영향을 줄이는 visual contrastive decoding(Leng et al., 2024) 등이 있다. Chapter 18의 classifier-free guidance와 같은 형태의 "조건 강조"이다.
VLM의 출력을 의사결정에 쓰려면 Chapter 21의 calibration과 Chapter 22의 평가 원칙이 그대로 적용된다. 생성된 문장에는 확률이 명시적으로 붙지 않으므로, 같은 질문을 여러 번 sampling해 답의 일치도를 보거나, yes/no 형태의 질문에서 token 확률을 confidence로 써서 reliability를 확인한다.
Efficiency와 Routing
Chapter 28분산 학습: DDP에서 FSDP와 Model Parallelism까지
새로 추가한 장 (강의 범위 밖). Li et al. 2020 (PyTorch DDP); Rajbhandari et al. 2020; Shoeybi et al. 2019; Huang et al. 2019; McCandlish et al. 2018
GPU 하나로 감당할 수 없는 model이나 data는 여러 GPU에 나눠 학습한다. 나누는 방법은 세 가지이다. Data를 나누는 data parallelism, parameter와 optimizer state를 나눠 저장하는 sharding, 그리고 model의 계산 자체를 나누는 tensor·pipeline parallelism이다. 이 장은 가장 기본인 PyTorch의 DistributedDataParallel(DDP)부터 시작해, 각 방법이 무엇을 나누고 그 대가로 어떤 통신을 하는지, 그리고 분산 학습이 통계적으로 batch 크기를 바꾸는 일이라는 점을 정리한다. Appendix A의 training loop를 여러 GPU로 확장하는 실무 지침도 함께 다룬다.
28.1Data parallelism과 DDP
GPU $N$개가 각각 model의 완전한 복사본을 갖고, 서로 다른 mini-batch $\mathcal B_k$($|\mathcal B_k|=b$)로 gradient를 계산한 뒤 평균해서 모두 같은 update를 한다.
각 GPU의 local gradient $\bg_k=\frac1b\sum_{i\in\mathcal B_k}\nabla\ell_i(\theta)$의 평균은 전체 batch $\mathcal B=\bigcup_k\mathcal B_k$ (크기 $B=Nb$)의 gradient와 같다: $$\frac1N\sum_{k=1}^N\bg_k=\frac1{Nb}\sum_{i\in\mathcal B}\nabla\ell_i(\theta).$$ 모든 GPU가 같은 $\theta$에서 시작해 같은 평균 gradient로 update하면, parameter는 GPU 사이에서 항상 같고 학습은 batch 크기 $B$의 단일 GPU SGD와 동일하다.
(BatchNorm처럼 batch 통계를 쓰는 layer는 예외이다. 각 GPU가 자기 batch $b$의 통계만 쓰므로 정확히 같지는 않다. GPU 사이에서 통계를 모으는 SyncBatchNorm을 쓰거나, batch에 의존하지 않는 LayerNorm·GroupNorm을 쓴다.)
평균을 계산하는 집단 통신이 all-reduce이다. 단순하게 한 GPU에 모았다가 다시 뿌리면 그 GPU의 통신량이 $N$에 비례해 병목이 된다. Ring all-reduce는 GPU를 고리로 잇고, gradient($M$ byte)를 $N$조각으로 나눈다. 처음 $N-1$ step에서는 각 GPU가 한 조각을 이웃에게 보내며 받은 조각을 더해(reduce-scatter) 끝나면 각 GPU가 서로 다른 한 조각의 완전한 합을 갖고, 다음 $N-1$ step에서 그 완성된 조각들을 돌려(all-gather) 모두가 전체 합을 갖는다. GPU 하나가 보내는 양은 $$2(N-1)\cdot\frac MN\approx2M$$ 으로 GPU 수와 거의 무관하다. 그래서 data parallelism은 통신 대역폭이 충분하면 GPU 수에 대해 잘 확장된다.
PyTorch DDP(Li et al., 2020)는 이를 효율적으로 구현한다. Gradient를 수십 MB 단위의 bucket으로 묶고, backward가 끝난 layer의 bucket부터 all-reduce를 시작해 나머지 backward 계산과 통신을 겹친다(overlap). 그래서 통신 시간이 대부분 계산 뒤에 숨는다. 학습 시작 시 rank 0의 parameter를 모든 GPU에 broadcast해 출발점을 맞춘다.
# torchrun --nproc_per_node=4 train.py (GPU 4개, process 4개)
import os, torch, torch.nn as nn, torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, DistributedSampler
dist.init_process_group("nccl") # torchrun이 RANK, WORLD_SIZE, LOCAL_RANK를 설정
local_rank = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)
model = SmallCNN().cuda(local_rank)
model = nn.SyncBatchNorm.convert_sync_batchnorm(model) # BatchNorm이 있으면 (선택)
model = DDP(model, device_ids=[local_rank])
sampler = DistributedSampler(train_set, shuffle=True) # process마다 겹치지 않는 1/N 부분
loader = DataLoader(train_set, batch_size=64, sampler=sampler, # 64는 GPU당 batch
num_workers=4, pin_memory=True)
optimizer = torch.optim.AdamW(model.parameters(), lr=base_lr) # 전체 batch 64*N에 맞춰 조정
for epoch in range(num_epochs):
sampler.set_epoch(epoch) # epoch마다 다른 shuffle (빠뜨리면 매 epoch 같은 순서)
model.train()
for x, y in loader:
x, y = x.cuda(local_rank, non_blocking=True), y.cuda(local_rank, non_blocking=True)
loss = criterion(model(x), y)
optimizer.zero_grad()
loss.backward() # 여기서 gradient all-reduce가 자동으로 일어남
optimizer.step()
if dist.get_rank() == 0: # 저장은 한 process만
torch.save(model.module.state_dict(), "ckpt.pt") # .module: DDP wrapper 안의 원래 model
dist.destroy_process_group()
자주 하는 실수
- Learning rate. 전체 batch가 GPU 수만큼 커진다. Chapter 5의 linear scaling rule에 따라 learning rate를 키우고 처음 몇 epoch는 warmup한다. 매우 큰 batch에서는 layer별로 update 크기를 정규화하는 LARS(You et al., 2017)·LAMB(You et al., 2020)가 쓰인다.
set_epoch누락. DistributedSampler의 shuffle seed가 epoch마다 바뀌지 않아 매 epoch 같은 순서로 학습한다.- 평가 data의 중복. DistributedSampler는 data 수가 GPU 수로 나누어떨어지지 않으면 앞쪽 sample을 반복해서 채운다. 1,001개를 GPU 4개로 평가하면 3개가 두 번 계산된다. 각 rank의 결과를 그대로 모아 평균하면 metric에 미세한 bias가 생기고, bootstrap 신뢰구간(Chapter 22)도 틀어진다. Index와 함께 예측을 all-gather해 중복을 제거하거나, 평가는 한 process에서 하는 것이 안전하다.
- Randomness. Process마다 다른 seed를 써야 data augmentation과 dropout이 GPU마다 달라진다. Model 초기화는 broadcast로 맞춰지므로 문제없다.
- Gradient accumulation. Memory가 부족해 micro-batch 여러 개의 gradient를 모아 한 번 update할 때, 중간 micro-batch에서는 all-reduce를 생략해야 통신이 낭비되지 않는다(
with model.no_sync():). 각 micro-batch의 loss를 accumulation 횟수로 나누면 큰 batch의 평균 gradient와 같다.
28.2Sharding: ZeRO와 FSDP
DDP에서는 모든 GPU가 parameter, gradient, optimizer state의 완전한 복사본을 갖는다. Chapter 29에서 자세히 보듯 Adam의 mixed precision 학습은 parameter당 약 16 byte(16-bit parameter 2 + gradient 2 + 32-bit master parameter와 두 moment 12)가 든다. 이 복사본들은 중복이다. ZeRO(Rajbhandari et al., 2020)는 이를 GPU 사이에 나눠(shard) 저장한다. Parameter 수 $\Psi$, GPU 수 $N$이면 GPU당 memory는 다음과 같다.
| 단계 | 나누는 것 | GPU당 memory | 7B, $N=8$ | 통신량 (DDP 대비) |
|---|---|---|---|---|
| DDP | 없음 | $16\Psi$ | 112 GB | 1× |
| ZeRO-1 | Optimizer state | $4\Psi+12\Psi/N$ | 38.5 GB | 1× |
| ZeRO-2 | + Gradient | $2\Psi+14\Psi/N$ | 26.3 GB | 1× |
| ZeRO-3 / FSDP | + Parameter | $16\Psi/N$ | 14 GB | 1.5× |
(Activation memory는 별도이다.) ZeRO-1, 2는 각 GPU가 자기가 맡은 parameter 조각의 optimizer state만 갖고 그 조각만 update한 뒤 결과를 나눈다. All-reduce를 reduce-scatter와 all-gather로 쪼개 쓰는 것이므로 통신량이 늘지 않는다. ZeRO-3는 parameter도 나눠 갖다가, 각 layer의 forward와 backward 직전에 all-gather로 그 layer의 parameter를 잠깐 모으고 쓰고 나면 버린다. PyTorch의 FSDP(fully sharded data parallel)가 이 방식이다. 통신은 1.5배로 늘지만 GPU 수에 반비례해 memory가 줄어, GPU 하나에 들어가지 않는 model도 data parallelism의 단순함을 유지한 채 학습할 수 있다.
28.3Model parallelism
Layer 하나의 weight나 activation이 GPU에 들어가지 않을 정도로 크거나, 통신 대역폭을 더 잘 쓰고 싶으면 계산 자체를 나눈다.
Tensor parallelism
Megatron-LM(Shoeybi et al., 2019)은 Transformer의 행렬 곱을 GPU에 나눈다. FFN $\mathbf Z=\mathrm{GELU}(\bX\bA)\mathbf B$에서 첫 행렬을 column으로 $\bA=[\bA_1,\bA_2]$ 나누면 $\mathrm{GELU}(\bX\bA)=[\mathrm{GELU}(\bX\bA_1),\mathrm{GELU}(\bX\bA_2)]$이다. GELU가 원소별 함수이므로 각 GPU가 통신 없이 자기 몫 $\mathbf Y_k=\mathrm{GELU}(\bX\bA_k)$를 계산할 수 있다. 둘째 행렬은 row로 $\mathbf B=\begin{pmatrix}\mathbf B_1\\\mathbf B_2\end{pmatrix}$ 나누면 $\mathbf Z=\mathbf Y_1\mathbf B_1+\mathbf Y_2\mathbf B_2$이므로 각 GPU의 부분합을 all-reduce 한 번으로 더하면 된다. Attention은 head 단위로 나눈다. Layer마다 forward와 backward에 all-reduce가 한 번씩 필요해 통신이 잦으므로, 보통 NVLink로 연결된 한 서버 안의 GPU끼리만 쓴다.
Pipeline parallelism
Model을 연속한 layer 묶음(stage) $p$개로 잘라 GPU마다 하나씩 맡긴다. 그대로 하면 한 번에 한 GPU만 일하므로, batch를 micro-batch $m$개로 나눠 앞 stage가 다음 micro-batch를 처리하는 동안 뒤 stage가 이전 micro-batch를 처리하게 한다(GPipe; Huang et al., 2019). 그래도 시작과 끝에 GPU가 쉬는 bubble이 남고, 그 비율은 $(p-1)/(m+p-1)$이다. Forward와 backward를 번갈아 배치하는 1F1B schedule(PipeDream; Harlap et al., 2018)은 저장해야 할 activation 수를 줄인다. 통신은 stage 경계의 activation뿐이라 서버 사이에도 쓸 수 있다.
대형 model 학습은 이들을 조합한다(3D parallelism). 서버 안에서는 tensor parallelism, 서버 사이에서는 pipeline parallelism, 그 바깥에 data parallelism(또는 FSDP)을 두는 식이다. Mixture of experts(Chapter 30)에서는 expert를 GPU에 나누고 token을 해당 GPU로 보내는 expert parallelism이 추가된다.
28.4Memory를 아끼는 다른 방법
- Activation checkpointing. Backward에 필요한 activation을 모두 저장하지 않고 일부 layer의 input만 저장했다가 backward 때 다시 계산한다. $L$개 layer를 $\sqrt L$개 구간으로 나누면 activation memory를 $O(\sqrt L)$로 줄이는 대신 forward를 한 번 더 한다(Chen et al., 2016).
- Mixed precision. BF16 계산과 FP32 master weight(Chapter 29).
- CPU offloading. Optimizer state를 CPU memory에 두고 update를 CPU에서 한다. 느리지만 GPU memory를 크게 아낀다.
28.5통계적 관점: batch 크기는 공짜가 아니다
Data parallelism은 결국 batch를 키우는 것이다. Batch를 두 배로 하면 step당 gradient의 noise가 절반(분산 $\propto1/B$)이 되어, 같은 learning rate라면 한 step이 더 정확하다. 그러나 이 이득은 끝없이 계속되지 않는다. McCandlish et al.(2018)은 per-sample gradient의 covariance $\bSigma$와 평균 gradient $\bG$로 정의한 gradient noise scale $$B_{\text{noise}}=\frac{\tr(\bSigma)}{\|\bG\|^2}$$ 을 기준으로, batch가 $B_{\text{noise}}$보다 훨씬 작으면 batch를 키울수록 필요한 step 수가 거의 비례해 줄고(완벽한 병렬화), 훨씬 크면 더 키워도 step 수가 거의 줄지 않아 계산만 낭비된다는 것을 보였다. 이 값은 noise 대비 신호의 비율이므로 학습이 진행되어 gradient가 작아질수록 커진다. 그래서 큰 model의 학습에서는 batch를 점점 키우는 schedule이 쓰인다. 또 Chapter 5에서 보았듯 큰 batch는 SGD noise를 줄여 sharp minimum으로 갈 위험이 있으므로, GPU를 늘려 batch를 키울 때는 learning rate와 warmup을 함께 조정하고 validation 성능을 다시 확인해야 한다.
28.6정리
| 상황 | 권장 |
|---|---|
| Model이 GPU 하나에 들어가고 학습을 빠르게 하고 싶다 | DDP (+ mixed precision) |
| Optimizer state 때문에 memory가 부족하다 | ZeRO-1/2 |
| Model 자체가 GPU 하나에 들어가지 않는다 | FSDP(ZeRO-3), activation checkpointing |
| 수백억 parameter 이상, 여러 서버 | Tensor(서버 내) + pipeline(서버 간) + data parallel |
| Fine-tuning만 한다 | 먼저 LoRA·QLoRA(Chapter 29)로 GPU 하나에 맞출 수 있는지 확인 |
Chapter 29Parameter-efficient Fine-tuning과 Quantization
새로 추가한 장 (강의 범위 밖). Houlsby et al. 2019; Hu et al. 2022; Dettmers et al. 2022, 2023; Frantar et al. 2023; Xiao et al. 2023
Foundation model(Chapter 12)은 크다. 70억 parameter model은 16-bit로 저장해도 14GB이고, 전부 fine-tuning하려면 그 몇 배의 memory가 든다. 이 장은 큰 model을 적은 자원으로 적응시키고(parameter-efficient fine-tuning, PEFT) 배포하는(quantization, pruning) 방법을 다룬다. Quantization은 결국 연속값을 유한 개의 값으로 반올림하는 것이고, 그 오차는 통계적으로 분석할 수 있다. 균등 양자화의 오차, quantile 기반의 NF4, Hessian을 이용한 GPTQ, 그리고 fine-tuning으로 얻은 작은 update가 양자화에서 어떻게 되는지를 차례로 본다.
29.1Memory는 어디에 쓰이는가
Parameter 수를 $P$라 하자. Adam으로 mixed precision 학습을 하면 parameter마다 16-bit weight(2 byte)와 gradient(2 byte), 그리고 32-bit master weight, 1차·2차 moment(각 4 byte)가 필요해 약 $16P$ byte가 든다(Rajbhandari et al., 2020). 70억 parameter면 112GB이고, 여기에 batch 크기와 sequence 길이에 비례하는 activation memory가 더해진다. 추론에는 weight만 있으면 되지만, 생성 중에는 이전 token의 key·value를 저장하는 KV cache가 sequence 길이에 비례해 늘어난다.
| 형식 | Bit (sign / exponent / mantissa) | 최댓값 | Machine epsilon | 용도 |
|---|---|---|---|---|
| FP32 | 1 / 8 / 23 | $3.4\times10^{38}$ | $2^{-23}\approx1.2\times10^{-7}$ | Master weight, optimizer state |
| FP16 | 1 / 5 / 10 | 65,504 | $2^{-10}\approx9.8\times10^{-4}$ | 학습(loss scaling 필요), 추론 |
| BF16 | 1 / 8 / 7 | $3.4\times10^{38}$ | $2^{-7}\approx7.8\times10^{-3}$ | 학습(FP32와 같은 range) |
| FP8 E4M3 / E5M2 | 1 / 4 / 3, 1 / 5 / 2 | 448 / 57,344 | $2^{-3}$ / $2^{-2}$ | 최신 GPU의 학습·추론 |
| INT8 / INT4 | 정수 | 127 / 7 (×scale) | 균등 간격 $s$ | 추론(weight, activation) |
Exponent bit는 표현 범위(dynamic range)를, mantissa bit는 상대 정밀도를 정한다. FP16은 범위가 좁아 작은 gradient가 0으로 underflow하므로 loss에 큰 상수를 곱했다가 gradient에서 나누는 loss scaling이 필요하다(Micikevicius et al., 2018). BF16은 정밀도를 희생하고 FP32와 같은 범위를 가져서 loss scaling 없이 학습할 수 있으므로 현재 대형 model 학습의 표준이다. 정수 형식은 균등한 간격의 격자이므로 표현 범위를 scale factor로 따로 정해야 한다.
29.2Parameter-efficient fine-tuning
Pre-trained weight $\bW_0$를 고정하고 소수의 parameter만 학습하면 gradient와 optimizer state가 그 소수에 대해서만 필요하므로 memory가 크게 준다. Task마다 작은 parameter 묶음만 저장하면 되므로 하나의 base model로 여러 task를 서비스할 수도 있다. 이 접근의 근거는 fine-tuning에 필요한 변화가 저차원이라는 관찰이다. Aghajanyan et al.(2021)은 pre-trained language model의 fine-tuning을 parameter 공간의 random한 저차원 subspace 안에서만 해도(수백~수천 차원) full fine-tuning 성능의 90%에 도달함을 보이고 이를 intrinsic dimension이라 불렀다. Pre-training이 잘 될수록 이 차원이 작아졌다.
| 방법 | 학습하는 것 | 추론 시 추가 비용 | 특징 |
|---|---|---|---|
| Adapter (Houlsby et al., 2019) | 각 block에 삽입한 bottleneck MLP $\bh\leftarrow\bh+\bW_{\uparrow}\sigma(\bW_{\downarrow}\bh)$ | 있음(층이 늘어남) | 최초의 PEFT, 구조가 단순 |
| Prefix / prompt tuning (Li & Liang, 2021; Lester et al., 2021) | 입력 앞(또는 각 layer의 key·value 앞)에 붙이는 연속 vector | Context 길이 증가 | Model이 클수록 full fine-tuning에 근접 |
| BitFit (Ben Zaken et al., 2022) | Bias만 | 없음 | Parameter 0.1% 미만 |
| LoRA (Hu et al., 2022) | $\bW_0+\frac\alpha r\mathbf B\mathbf A$의 low-rank 행렬 | 없음(merge 가능) | 가장 널리 쓰임, Chapter 12 |
| DoRA (Liu et al., 2024) | Weight를 크기와 방향으로 분해하고, 방향은 LoRA로, 크기는 직접 학습 | 없음(merge 가능) | LoRA보다 full fine-tuning에 가까운 update 양상 |
LoRA의 $\mathbf B$를 0으로 초기화하므로 학습 시작 시점의 model은 pre-trained model과 정확히 같다. Scaling $\alpha/r$은 rank를 바꿔도 학습률을 다시 조정하지 않아도 되게 하려는 것인데, rank가 클 때는 $\alpha/\sqrt r$이 학습을 더 안정시킨다는 분석도 있다(rsLoRA; Kalajdzievski, 2023). 학습이 끝나면 $\bW=\bW_0+\frac\alpha r\mathbf B\mathbf A$로 합쳐(merge) 추가 비용 없이 추론할 수 있다. 이 merge가 양자화와 만날 때 생기는 문제는 뒤에서 다룬다.
29.3균등 양자화와 그 오차
Bit 수 $b$, scale $s>0$, zero-point $z$에 대해 $$q(x)=\mathrm{clamp}\Big(\Big\lfloor\frac xs\Big\rceil+z,\ q_{\min},\ q_{\max}\Big),\qquad\hat x=s\,(q(x)-z).$$ $\lfloor\cdot\rceil$는 반올림이다. $z=0$이고 정수 범위가 $\{-L,\dots,L\}$, $L=2^{b-1}-1$이면 symmetric quantization이며, 표현 범위 $[-\alpha,\alpha]$에 대해 $s=\alpha/L$이다.
양자화 오차는 범위 안의 값에 대한 rounding 오차와 범위 밖의 값을 잘라서 생기는 clipping 오차로 나뉜다.
범위 안의 $x$에 대해 $|x-\hat x|\le s/2$이다. $x$의 분포가 간격 $s$에 비해 충분히 매끄러워 $x$의 격자 안 위치가 $[0,s)$에서 uniform이라고 근사하면, rounding 오차는 $\mathrm{Uniform}(-s/2,s/2)$이고 $$\E\big[(x-\hat x)^2\big]=\frac{s^2}{12}=\frac{\alpha^2}{12L^2}.$$ Bit를 하나 늘리면 $L$이 약 두 배가 되어 MSE가 약 1/4로(신호 대 잡음비가 약 6 dB) 줄어든다.
$e\sim\mathrm{Uniform}(-s/2,s/2)$이면 $\E e^2=\frac1s\int_{-s/2}^{s/2}e^2\,\dd e=s^2/12$. $L=2^{b-1}-1$이므로 $b\to b+1$에서 $L\approx2L$.
$\alpha$를 키우면 clipping 오차는 줄지만 $s$가 커져 rounding 오차가 커진다. Bit 수가 적을수록 최적의 $\alpha$는 작아진다. 표준정규분포 weight에서 수치적으로 구한 최적값은 2-bit(정수 $\{-1,0,1\}$)에서 $\alpha\approx1.25\sigma$, 3-bit에서 $1.95\sigma$, 4-bit에서 $2.47\sigma$이고 그때의 MSE는 각각 $0.19\sigma^2$, $0.047\sigma^2$, $0.013\sigma^2$이다. 단순히 최댓값으로 범위를 정하는(absmax) 것은 꼬리가 무거운 분포에서 대부분의 값에 대해 해상도를 낭비한다(Banner et al., 2019).
Granularity
Scale을 몇 개의 값이 공유하는가도 중요하다. Tensor 전체가 하나의 scale을 쓰는 per-tensor, output channel(weight 행렬의 row)마다 쓰는 per-channel, 연속한 64–128개 weight마다 쓰는 per-group(block) 양자화가 있다. Channel마다 weight 크기가 크게 다르면 per-tensor scale은 작은 channel의 해상도를 버린다. Scale 자체도 저장해야 하므로, block 크기 64에 FP32 scale을 쓰면 parameter당 $32/64=0.5$ bit가 추가된다.
Quantile quantization과 NF4
균등 격자는 값이 많이 몰린 0 근처와 드문 꼬리에 같은 해상도를 준다. 분포를 안다면 격자를 분포에 맞추는 것이 낫다. CDF $F$가 연속인 확률변수를 $F^{-1}(k/2^b)$ 같은 quantile로 나누면 $2^b$개의 구간에 같은 확률이 할당되어 code가 균등하게 쓰인다(code의 entropy가 최대 $b$ bit). Pre-trained weight는 대략 0 중심의 정규분포를 따르므로, QLoRA(Dettmers et al., 2023)는 표준정규분포의 quantile로 만든 16개 값을 $[-1,1]$로 정규화한 NF4(4-bit NormalFloat)를 제안했다. 0을 정확히 표현하도록 음수 쪽 8개, 양수 쪽 9개의 quantile을 따로 잡고 0을 공유해 16개를 만든다. 각 block(64개)을 absmax로 $[-1,1]$에 맞춘 뒤 가장 가까운 NF4 값으로 보낸다. 정규분포 weight를 block 64로 양자화한 simulation에서 NF4의 MSE는 $0.0085\sigma^2$로, 같은 block absmax의 균등 INT4($0.0116\sigma^2$)보다 약 27% 작았다. QLoRA는 block scale까지 다시 8-bit로 양자화하는 double quantization으로 scale 부담을 parameter당 0.5 bit에서 약 0.127 bit로 줄였다.
29.4Activation과 outlier
Weight만 양자화하면(weight-only) memory와 memory bandwidth가 줄고, 계산은 dequantize한 뒤 16-bit로 한다. Activation까지 8-bit로 양자화하면(W8A8) 정수 행렬 곱 hardware를 써서 계산 자체가 빨라진다. 어려움은 activation에 있다. Dettmers et al.(2022)은 대형 language model의 hidden state에서 소수의 feature 차원이 다른 차원보다 훨씬 큰 값을 체계적으로 갖고, 이런 outlier feature가 약 6.7B parameter 규모부터 거의 모든 layer에 나타난다는 것을 발견했다. Token별 per-tensor scale을 쓰면 이 몇 개의 차원 때문에 나머지 값의 해상도가 무너진다. 그들의 LLM.int8()은 outlier 차원만 16-bit로, 나머지를 8-bit로 계산하는 혼합 분해로 이를 해결했다.
SmoothQuant(Xiao et al., 2023)는 수학적으로 동등한 변환으로 어려움을 옮긴다. 임의의 양수 대각 행렬 $\diag(\mathbf c)$에 대해 $$\mathbf Y=\bX\bW=\big(\bX\diag(\mathbf c)^{-1}\big)\big(\diag(\mathbf c)\bW\big)$$ 이므로, outlier가 있는 activation channel $j$를 $c_j$로 나누고 그만큼 weight의 해당 row에 곱한다. $c_j=\max|\bX_{:,j}|^{a}/\max|\bW_{j,:}|^{1-a}$ ($a\approx0.5$)로 두면 양쪽의 최댓값이 비슷해져 둘 다 8-bit로 양자화하기 쉬워진다. 변환은 이전 layer의 normalization parameter에 흡수할 수 있어 추론 비용이 없다. AWQ(Lin et al., 2024)도 비슷한 per-channel scaling을 weight-only 양자화에 적용해, activation이 큰 소수의 중요한 weight channel을 보호한다.
29.5Post-training quantization: GPTQ
학습이 끝난 model을 재학습 없이 소량의 calibration data만으로 양자화하는 것을 post-training quantization(PTQ)이라 한다. 가장 단순한 round-to-nearest(RTN)는 weight를 하나씩 독립적으로 반올림한다. 그러나 한 weight의 오차를 같은 row의 다른 weight가 보상할 수 있다. Layer의 output을 보존하는 것을 목표로 하면, calibration input $\bX\in\R^{d\times N}$에 대해 row $\bw$마다 $$\min_{\hat\bw\in\text{grid}}\ \|(\hat\bw-\bw)^\top\bX\|^2=(\hat\bw-\bw)^\top\mathbf H(\hat\bw-\bw),\qquad\mathbf H=\bX\bX^\top$$ 를 풀어야 한다. 정수 격자 위의 이 문제는 어렵지만, 한 좌표씩 고정해 가며 나머지를 최적으로 조정하는 것은 closed form이다.
좌표 $q$를 $\hat w_q=\mathrm{quant}(w_q)$로 고정하고 나머지 좌표를 자유롭게 바꿀 때, $\delta\bw=\hat\bw-\bw$에 대한 $\delta\bw^\top\mathbf H\delta\bw$의 최소화 해와 최솟값은 $$\delta\bw=-\frac{w_q-\mathrm{quant}(w_q)}{[\mathbf H^{-1}]_{qq}}\,\mathbf H^{-1}\mathbf e_q,\qquad\min=\frac{\big(w_q-\mathrm{quant}(w_q)\big)^2}{[\mathbf H^{-1}]_{qq}}.$$
제약 $\mathbf e_q^\top\delta\bw=\mathrm{quant}(w_q)-w_q=:-\varepsilon$ 아래 $\delta\bw^\top\mathbf H\delta\bw$를 최소화한다. Lagrangian의 stationary 조건 $2\mathbf H\delta\bw=\lambda\mathbf e_q$에서 $\delta\bw=\frac\lambda2\mathbf H^{-1}\mathbf e_q$이고, 제약에 넣으면 $\frac\lambda2=-\varepsilon/[\mathbf H^{-1}]_{qq}$. 대입하면 최솟값 $\varepsilon^2/[\mathbf H^{-1}]_{qq}$를 얻는다.
Hassibi & Stork(1993)의 Optimal Brain Surgeon은 이를 pruning(quant를 0으로)에 썼다. GPTQ(Frantar et al., 2023)는 모든 row에서 같은 순서로 column을 하나씩 양자화하고, 그때마다 아직 양자화하지 않은 column들을 위 식으로 보정한다. 고정된 좌표를 제거한 뒤의 $\mathbf H^{-1}$은 Schur complement로 update하며, column 순서가 모든 row에 공통이므로 $\mathbf H^{-1}$을 공유해 수천억 parameter model도 몇 시간 안에 양자화한다. 상관된 input을 받는 $256\times256$ layer를 4-bit per-channel로 양자화한 실험에서 output의 상대 재구성 오차가 RTN 1.58%에서 GPTQ 0.77%로 절반 이하가 되었다. $\mathbf H$가 input의 2차 moment이므로, 이는 input distribution 아래에서의 weighted least squares라고 볼 수 있다.
29.6Quantization-aware training
PTQ로 부족하면 양자화를 포함한 채 학습한다(QAT). Forward에서 weight와 activation을 양자화했다가 바로 dequantize(fake quantization)하여 양자화 오차를 학습 중에 겪게 한다. 문제는 반올림의 미분이 거의 모든 곳에서 0이라는 것이다. Straight-through estimator(STE; Bengio et al., 2013)는 backward에서 반올림을 항등함수로 취급한다($\partial\lfloor x\rceil/\partial x:=1$, clipping 범위 밖에서는 0). 기댓값 수준에서 정당화되는 estimator는 아니지만 실제로 잘 작동한다. LSQ(Esser et al., 2020)는 scale $s$도 gradient로 학습한다. QAT는 비싸지만 4-bit 이하에서 PTQ보다 확실히 낫다.
29.7PEFT와 양자화를 함께 쓸 때
QLoRA. Dettmers et al.(2023)은 base model을 NF4로 양자화해 고정하고, 그 위에 BF16 LoRA adapter를 학습한다. Forward와 backward에서 base weight를 그때그때 dequantize하므로 gradient는 양자화된 base를 통과해 adapter로 간다. 즉 adapter는 처음부터 양자화된 base model 위에서 학습된다. Memory spike를 GPU와 CPU 사이에서 page로 옮기는 paged optimizer까지 더해, 65B model을 48GB GPU 하나에서 fine-tuning했다.
Merge 후 양자화의 문제. 반대로 full precision에서 LoRA를 학습하고, merge한 $\bW_0+\Delta\bW$를 나중에 양자화하면 어떻게 될까? Fine-tuning의 변화 $\Delta\bW$는 보통 $\bW_0$보다 훨씬 작다.
간격 $s$인 반올림 $q$에 대해, $w$의 격자 안 위치가 $[0,s)$에서 uniform이라 하자. $\Delta/s$의 소수 부분을 $f$라 하면 $$\E\big[q(w+\Delta)-q(w)\big]=\Delta,\qquad\Var\big(q(w+\Delta)-q(w)\big)=s^2f(1-f).$$ 특히 $0\le\Delta\lt s$이면 $q(w+\Delta)-q(w)$는 확률 $\Delta/s$로 $s$, 나머지는 0이다.
$\Delta=ms+fs$ ($m$은 정수)라 하면 $q(w+\Delta)-q(w)=ms+\big(q(w+fs)-q(w)\big)$이다. $w$의 격자 안 위치 $u\sim\mathrm{Uniform}[0,s)$에서 반올림 경계를 넘는 것은 $u$가 경계까지 $fs$ 이내에 있을 때이므로 확률 $f$로 $s$만큼 더 커진다. 따라서 평균은 $ms+fs=\Delta$이고 분산은 Bernoulli$(f)$에 $s^2$를 곱한 $s^2f(1-f)$이다.
즉 양자화 후에도 update는 평균적으로 보존되지만(unbiased), $\Delta\ll s$이면 각 weight의 update는 대부분 사라지고 일부만 한 칸씩 크게 바뀌는 매우 noisy한 형태로 남는다. 더 근본적으로, base weight 자체의 양자화 오차 $(\mathrm Q(\bW)-\bW)\bx$가 fine-tuning이 만든 변화 $\Delta\bW\bx$와 같은 크기이거나 더 크다. 예를 들어 $1024\times1024$ Gaussian weight에 $\|\Delta\bW\|_F/\|\bW\|_F=1\%$인 rank-16 update를 더한 합성 예에서, per-channel INT8 양자화의 output 오차는 $\|\Delta\bW\bx\|$의 약 0.8배, INT4에서는 약 14배였다. Adapter를 merge하지 않고 16-bit로 따로 두어도 이 base 오차는 그대로 남는다(합성 예에서 전체 오차가 거의 같았다). Base model의 출력 전체에 비하면 작은 오차이지만, task 성능이 그 작은 $\Delta\bW$에 의존한다면 영향은 클 수 있다. 실제 영향은 task의 decision margin 중 얼마가 fine-tuning에서 왔는지에 달려 있으므로, 양자화 전후의 task 성능을 직접 측정해야 한다(Chapter 22의 paired 비교).
대응책은 adapter가 양자화 오차를 학습 중에 보게 하는 것이다. (1) QLoRA처럼 양자화된 base 위에서 adapter를 학습하거나, (2) LoftQ(Li et al., 2024)처럼 $\mathrm Q$와 low-rank 성분을 번갈아 $\min\|\bW-\mathrm Q-\mathbf B\mathbf A\|_F$로 맞춰 양자화 오차를 LoRA 초기값으로 보상하거나, (3) QAT를 하거나, (4) 오차에 민감한 layer만 높은 정밀도로 남기는 mixed precision을 쓴다. PTQ를 쓴다면 calibration data를 fine-tuning한 task의 data로 잡아야 GPTQ의 $\mathbf H$가 실제 input 분포를 반영한다.
29.8Pruning
Weight의 일부를 0으로 만드는 pruning도 오래된 압축 방법이다. 크기가 작은 weight부터 지우는 magnitude pruning이 기본이며, 위의 Optimal Brain Surgeon 식은 지울 weight를 고르고 나머지를 보정하는 원리를 준다. SparseGPT(Frantar & Alistarh, 2023)는 GPTQ와 같은 방식으로 175B model을 재학습 없이 50% sparsity로 만들면서 perplexity 증가를 작게 유지했다. Lottery ticket hypothesis(Frankle & Carbin, 2019)는 큰 random network 안에 처음부터 따로 학습해도 같은 성능을 내는 작은 sub-network가 있다는 관찰이다. 실제 속도 향상은 sparsity의 구조에 달려 있다. 임의 위치의 0(unstructured)은 일반 hardware에서 빠르지 않고, 연속한 4개 중 2개를 0으로 하는 2:4 sparsity처럼 hardware가 지원하는 구조나 channel·head 단위 제거(structured)가 필요하다. 작은 model로 지식을 옮기는 knowledge distillation(Chapter 12)은 이들과 함께 쓰이는 세 번째 축이다.
29.9정리
| 목표 | 방법 | 통계적 핵심 |
|---|---|---|
| 적은 memory로 적응 | LoRA, adapter, prompt tuning | Fine-tuning update의 낮은 intrinsic dimension |
| Weight memory 절감 | INT8/INT4/NF4 weight-only PTQ | Rounding 오차 $s^2/12$, clipping trade-off, quantile coding |
| 정확한 저비트 PTQ | GPTQ, AWQ | Input 2차 moment로 가중한 least squares |
| 계산 가속 | W8A8, SmoothQuant, FP8 | Outlier channel의 scale 재분배 |
| 극저비트·최고 정확도 | QAT, LoftQ, QLoRA | 학습 중 양자화 오차를 보게 함 |
여러 model을 두고 input마다 하나를 고르는 routing에서는 모든 model을 memory에 올려야 하므로 이 장의 압축 기법이 직접 필요해진다. 다음 장에서 다룬다.
Chapter 30Routing과 Mixture of Experts
새로 추가한 장 (강의 범위 밖). Jacobs et al. 1991; Shazeer et al. 2017; Fedus et al. 2022; Jiang et al. 2024; Leviathan et al. 2023; Mozannar & Sontag 2020
Ensemble(Chapter 21)은 여러 model의 예측을 모두 계산해 평균한다. 정확하지만 비용이 model 수만큼 든다. Routing은 input마다 일부 model(또는 model 안의 일부 sub-network)만 골라 계산한다. 같은 계산량으로 더 큰 capacity를 쓰거나, 같은 capacity를 더 적은 계산으로 쓰는 것이 목적이다. 이 장은 routing을 세 수준에서 다룬다. Model 내부에서 token마다 expert를 고르는 sparse mixture of experts(MoE), 따로 학습된 여러 model 중 input마다 하나를 고르는 model-level routing, 그리고 싼 model과 비싼 model을 순서대로 쓰는 cascade와 speculative decoding이다. 공통 질문은 "어느 expert가 이 input에 맞는지를 input만 보고 얼마나 잘 예측할 수 있는가"이다.
30.1Mixture of experts: 통계 model로서
Mixture of experts(Jacobs et al., 1991)는 input에 따라 mixture weight가 바뀌는 mixture model이다. $$p(y\mid\bx)=\sum_{k=1}^Kg_k(\bx)\,p_k(y\mid\bx),\qquad\mathbf g(\bx)=\softmax(\mathbf u(\bx)).$$ $p_k$는 expert, $\mathbf g$는 gating network이다. Gaussian mixture가 고정된 weight $\pi_k$를 쓰는 것과 달리 weight가 $\bx$의 함수이므로, input 공간을 나눠 각 영역을 다른 expert가 맡는다. Latent variable "어느 expert가 이 data를 생성했는가"를 두면 Gaussian mixture처럼 EM algorithm으로 MLE를 구할 수 있다.
Posterior responsibility $h_k(\bx,y)=\dfrac{g_k(\bx)p_k(y\mid\bx)}{\sum_jg_j(\bx)p_j(y\mid\bx)}$에 대해 $$\frac{\partial\log p(y\mid\bx)}{\partial u_k}=h_k-g_k,\qquad\nabla_{\theta_k}\log p(y\mid\bx)=h_k\,\nabla_{\theta_k}\log p_k(y\mid\bx).$$
$\log p=\log\sum_je^{u_j}p_j-\log\sum_je^{u_j}$이므로 $\partial/\partial u_k$는 $\frac{e^{u_k}p_k}{\sum_je^{u_j}p_j}-\frac{e^{u_k}}{\sum_je^{u_j}}=h_k-g_k$. Expert parameter $\theta_k$에 대해서는 $\frac{g_k\nabla p_k}{p}=h_k\nabla\log p_k$.
Gate는 사후확률 $h_k$(실제로 이 data를 잘 설명한 expert)를 사전 확률 $g_k$로 따라가도록 학습되고(softmax–CE의 $\bp-\by$와 같은 형태), 각 expert는 자신이 책임진 정도 $h_k$만큼 가중된 data로 학습된다. EM의 E-step이 $h_k$ 계산, M-step이 가중 MLE에 해당한다. 이 "책임을 나누는" 구조가 이후 모든 routing의 원형이다.
30.2Sparse MoE in Transformers
현대의 MoE는 Transformer block의 FFN을 expert $N$개로 바꾸고, token마다 router가 상위 $k$개(보통 1–2개)만 골라 계산한다(Shazeer et al., 2017). $$\mathbf y=\sum_{i\in\mathcal T_k(\bx)}\tilde g_i(\bx)\,E_i(\bx),\qquad\mathcal T_k(\bx)=\text{top-}k\big(\bW_r\bx\big),\qquad\tilde g_i=\frac{e^{(\bW_r\bx)_i}}{\sum_{j\in\mathcal T_k}e^{(\bW_r\bx)_j}}.$$ Parameter 수는 expert 수에 비례해 늘지만 token당 계산은 $k$개 expert분이다. Switch Transformer(Fedus et al., 2022)는 $k=1$로도 같은 계산량의 dense model보다 학습이 몇 배 빠름을 보였다. Mixtral 8×7B(Jiang et al., 2024)는 expert 8개 중 2개를 써서 전체 약 47B parameter 중 token당 약 13B만 활성화하고, DeepSeek-V3(2024)는 전체 671B 중 37B만 활성화한다. 다만 모든 expert의 weight는 memory에 있어야 하므로 MoE는 계산을 줄일 뿐 memory를 줄이지는 않는다. 여러 GPU에 expert를 나눠 두고 token을 해당 GPU로 보내는 expert parallelism이 필요하며, 그 통신 비용이 실제 속도를 좌우한다.
Load balancing
Router를 그대로 학습하면 소수의 expert가 대부분의 token을 받는 불균형이 생긴다. 초기에 조금 더 선택된 expert가 더 많이 학습되어 더 좋아지고, 그래서 더 자주 선택되는 rich-get-richer 동역학 때문이다. 선택받지 못한 expert는 학습되지 않는다. 이를 막기 위해 auxiliary loss를 더한다(Fedus et al., 2022). Batch의 token $T$개에 대해 expert $i$로 보내진 token 비율 $f_i$와 router 확률의 평균 $P_i$로 $$\L_{\text{aux}}=\alpha\,N\sum_{i=1}^Nf_i\,P_i,\qquad f_i=\frac1T\sum_{t}\ind\big[\argmax\mathbf g(\bx_t)=i\big],\quad P_i=\frac1T\sum_tg_i(\bx_t).$$ $f_i$는 미분할 수 없지만 $P_i$를 통해 gradient가 흐른다. 많이 쓰인 expert($f_i$가 큰)의 확률을 낮추는 방향이다. $f=P$라고 놓으면 $N\sum_iP_i^2\ge N\cdot\frac1N=1$(Cauchy–Schwarz)이고 등호는 균등 분배 $P_i=1/N$에서 성립하므로, 이 loss는 균등한 사용을 선호한다.
그 밖의 장치들은 다음과 같다. 각 expert가 처리할 수 있는 token 수에 상한(capacity factor × $T/N$)을 두고 넘치는 token은 residual connection으로만 통과시킨다(token dropping). Router logit의 크기를 억제하는 z-loss $\frac1T\sum_t(\log\sum_je^{u_{tj}})^2$는 수치 안정성을 높인다(Zoph et al., 2022). Token이 expert를 고르는 대신 expert가 상위 token을 고르는 expert-choice routing(Zhou et al., 2022)은 균형을 구조적으로 보장한다. DeepSeekMoE(Dai et al., 2024)는 expert를 잘게 나누고 항상 활성화되는 shared expert를 두어 공통 지식과 전문 지식을 분리했고, DeepSeek-V3는 auxiliary loss 대신 expert마다 bias를 routing 점수에 더해 과부하된 expert의 bias를 조금씩 낮추는 방식으로 균형을 맞춘다(Wang et al., 2024). Loss에 다른 항을 더하지 않아 주 objective를 왜곡하지 않는다는 것이 장점이다. 흥미롭게도 Mixtral의 분석에서 expert는 주제(수학, 생물 등)보다 문법적·표면적 token 특성에 따라 나뉘는 경향을 보였다. "전문가"라는 이름이 의미 단위의 전문화를 보장하지는 않는다.
30.3Model-level routing
이번에는 따로 학습된 $K$개의 model $f_1,\dots,f_K$(예: 서로 다른 foundation model을 각각 fine-tuning한 것)가 있고, input마다 하나를 골라 그 예측을 쓰는 router $r:\mathcal X\to\{1,\dots,K\}$를 생각한다. 동기는 model들이 서로 다른 sample을 맞힌다는 관찰이다. 어떤 model도 모든 sample을 맞히지는 못하지만, 각 sample을 맞히는 model이 하나라도 있는 비율("oracle accuracy")은 최고 단일 model의 정확도보다 높다. 그 차이가 routing으로 얻을 수 있는 이득처럼 보인다. 그러나 그 상한은 정확히 따져야 한다.
$\eta_k(\bx)=P\big(f_k(X)=Y\mid X=\bx\big)$를 model $k$의 조건부 정확도라 하자. 임의의 router $r$의 정확도는 $\E\big[\eta_{r(X)}(X)\big]$이고, 따라서 최적 router는 $$r^\ast(\bx)=\argmax_k\eta_k(\bx),\qquad\mathrm{Acc}(r^\ast)=\E\big[\max_k\eta_k(X)\big]$$ 이다. 이는 per-sample oracle의 정확도 $P\big(\exists k:f_k(X)=Y\big)$ 이하이며, 비용 $c_k$를 고려하면 $r^\ast_\lambda(\bx)=\argmax_k\{\eta_k(\bx)-\lambda c_k\}$이다.
$P(f_{r(X)}(X)=Y)=\E\big[P(f_{r(X)}(X)=Y\mid X)\big]=\E[\eta_{r(X)}(X)]$이고, 각 $\bx$에서 $\eta_{r(\bx)}(\bx)\le\max_k\eta_k(\bx)$이다. 또 $\max_kP(A_k\mid\bx)\le P(\bigcup_kA_k\mid\bx)$ ($A_k=\{f_k(\bx)=Y\}$)에서 oracle 이하임이 나온다. 비용이 있는 경우도 같은 pointwise 최대화이다.
Oracle은 정답 $Y$를 본 뒤에 model을 고르는 것이므로 어떤 router도 도달할 수 없다. 극단적인 예로 두 model이 모든 input에서 독립적으로 0.8의 확률로 맞힌다면 oracle accuracy는 $1-0.2^2=0.96$이지만 $\eta_1=\eta_2=0.8$이므로 최적 router도 0.8에 그친다. Model 사이의 차이가 input $\bx$로 예측 가능한 차이(어떤 종류의 input에서 어떤 model이 체계적으로 낫다)일 때만 routing이 이득을 준다. 반대로 model들이 서로 다른 sample을 맞히는 것이 우연(label noise, 경계 근처의 sample)이라면 그 차이는 ensemble로만 활용할 수 있다. 따라서 routing을 설계하기 전에 각 model의 정오답을 target으로 하는 간단한 classifier가 chance 이상으로 예측하는지부터 확인하는 것이 좋다.
Router 학습
정리에 따르면 router가 할 일은 $\eta_k(\bx)$의 추정이다. 실무에서 주의할 점은 다음과 같다.
- Target의 정의. "가장 좋은 model 하나"를 label로 하는 multiclass classification은 여러 model이 맞거나 모두 틀린 sample에서 label이 정의되지 않는다. Model마다 정오답 $Z_k=\ind[f_k(X)=Y]$를 target으로 하는 $K$개의 binary head를 BCE로 학습하면, BCE가 proper scoring rule(Chapter 21)이므로 각 head가 $\eta_k(\bx)$를 consistent하게 추정한다. 정오답 대신 각 model의 loss(예: NLL)를 regression하고 예측 loss가 가장 작은 model을 고를 수도 있다. 이 target은 정답 여부보다 정보가 많고 noise가 적다.
- Label을 만드는 data. $Z_k$를 model $f_k$가 학습한 data에서 계산하면 거의 모두 1이 되어 router가 배울 것이 없거나 잘못 배운다. Expert의 학습에 쓰지 않은 data에서 계산해야 하며, data가 부족하면 cross-validation처럼 fold를 나눠 각 fold의 label을 그 fold를 보지 않은 expert로 만드는 cross-fitting을 쓴다. 또 label은 실제 배포와 같은 조건(전처리, input 해상도 등)에서 expert를 실행해 만들어야 한다.
- Router의 input과 비용. Router는 expert를 실행하기 전에 결정해야 하므로 expert보다 훨씬 싸야 한다. 작은 별도 network를 쓰거나, 공통의 가벼운 backbone feature, metadata(촬영 장비, 출처 등)를 쓴다. Router가 expert와 비슷한 크기라면 그 자원으로 더 큰 단일 model이나 ensemble을 쓰는 편이 나을 수 있다.
- 평가. Router의 이득은 "항상 최고 단일 model을 쓰는 것"(trivial router)과 같은 test set에서 paired로 비교해야 한다(Chapter 22의 McNemar test, paired bootstrap). 정확도와 함께 각 expert가 선택된 비율, 그리고 비용–정확도 곡선을 보고한다. 이론적 상한으로는 oracle accuracy 대신 위 정리의 $\E[\max_k\eta_k]$에 가까운 추정치를 써야 한다.
여러 model을 input마다 고르는 아이디어는 통계적 학습에서 dynamic classifier selection이라는 이름으로 오래 연구되었다(Cruz et al., 2018). 최근에는 language model 사이의 routing(예: 질문마다 작은 model과 큰 model 중 하나를 골라 비용을 줄이는 RouteLLM; Ong et al., 2024)으로 다시 주목받는다. 여러 model을 모두 memory에 두어야 하므로 Chapter 29의 양자화와 함께 쓰이는 경우가 많다.
Learning to defer
Routing의 대상이 model이 아니라 사람일 수도 있다. Model이 스스로 예측하거나, 불확실하면 전문가에게 넘기는(defer) 결정을 함께 학습하는 것을 learning to defer라 한다(Madras et al., 2018). 사람의 정확도도 input에 따라 다르므로, 위 정리에서 $K$개 model 중 하나를 사람으로 둔 것과 같다. Mozannar & Sontag(2020)은 $K+1$개 출력(class들과 "defer")을 갖는 softmax에 대한 consistent surrogate loss를 제시했다. Chapter 21의 selective prediction이 "넘긴 뒤 누가 처리하는가"를 고려하지 않는 것과 달리, 넘겨받는 쪽의 능력을 함께 고려한다.
30.4Cascade, early exit, speculative decoding
모든 input에 같은 계산이 필요하지는 않다. 쉬운 input은 작은 model로 충분하다.
- Cascade. 싼 model을 먼저 실행하고, confidence가 threshold $\tau$보다 낮을 때만 비싼 model을 부른다. 기대 비용은 $c_1+P(\text{conf}\lt\tau)\,c_2$이다. 이 규칙이 잘 작동하려면 confidence가 calibrated되어 있어야 한다(Chapter 21). Language model API를 비용 순서로 이어 붙인 FrugalGPT(Chen et al., 2023)가 예이다.
- Early exit. 한 network의 중간 layer마다 classifier를 달아, 충분히 확신하면 거기서 멈춘다(BranchyNet; Teerapittayanon et al., 2016). Cascade를 하나의 model 안에서 구현한 것이다.
Language model의 생성에서는 작은 model로 미리 쓰고 큰 model로 확인하는 speculative decoding(Leviathan et al., 2023; Chen et al., 2023)이 쓰인다. 작은 draft model $q$가 token 여러 개를 순차적으로 제안하면, 큰 model $p$가 그것들을 한 번의 forward pass로 병렬 평가하고 아래 규칙으로 받아들이거나 고친다. 놀라운 점은 출력의 distribution이 큰 model만 쓴 것과 정확히 같다는 것이다.
$x\sim q$를 뽑아 확률 $\min\big(1,p(x)/q(x)\big)$로 받아들이고, 거절되면 $p'(x)=\dfrac{\max(0,p(x)-q(x))}{\sum_{x'}\max(0,p(x')-q(x'))}$에서 다시 뽑는다. 최종 출력의 distribution은 정확히 $p$이고, 받아들일 확률은 $\beta=\sum_x\min(p(x),q(x))=1-\mathrm{TV}(p,q)$이다.
$P(\text{accept},x)=q(x)\min(1,p(x)/q(x))=\min(p(x),q(x))$이므로 받아들일 확률은 $\beta=\sum_x\min(p,q)$. 거절 확률은 $1-\beta=\sum_x(p-\min(p,q))=\sum_x\max(0,p-q)$이다. 따라서 $P(\text{output}=x)=\min(p,q)+(1-\beta)\frac{\max(0,p-q)}{1-\beta}=\min(p,q)+\max(0,p-q)=p(x)$.
Rejection sampling의 변형이다. 두 model이 비슷할수록(total variation이 작을수록) 많은 token이 받아들여져, 큰 model의 forward pass 한 번으로 여러 token을 생성한다. 품질 손실 없이 속도를 2–3배 높이는 방법으로 널리 쓰인다.
30.5정리
| 수준 | 무엇을 고르나 | Router 학습 신호 | 주요 위험 |
|---|---|---|---|
| Sparse MoE | Token마다 FFN expert | End-to-end gradient + load balancing | Expert 붕괴, 불균형, memory |
| Model-level routing | Input마다 독립 model | Expert별 정오답·loss 추정 ($\eta_k$) | 예측 불가능한 상보성, label leakage |
| Learning to defer | Model 또는 사람 | Defer class를 포함한 surrogate loss | 사람의 정확도 추정 |
| Cascade, early exit | 계산을 더 할지 | Confidence threshold | Calibration 실패 |
| Speculative decoding | Draft token을 받을지 | (학습 없음) $\min(1,p/q)$ | 없음(정확한 sampling), 속도만 차이 |
Routing은 "평균 내기"(ensemble)와 "하나 쓰기"(single model) 사이의 선택이다. 통계적으로는 input별 조건부 성능 $\eta_k(\bx)$를 얼마나 잘 추정하느냐의 문제로 환원되며, 그 추정이 chance보다 나아야만 비용을 들일 가치가 있다.
Practice
Appendix APyTorch로 학습하기
Lecture Week 05 (1.1), Week 06, Week 15
본문의 개념이 실제 code에서 어떻게 대응되는지 정리한다. 전체 흐름은 Dataset → DataLoader → Model → Loss → Optimizer(+scheduler) → training loop이다. 마지막에 data I/O와 hardware에 관한 실무 조언을 덧붙인다.
A.1구성 요소
| 구성 요소 | PyTorch | 본문 |
|---|---|---|
| Dataset (train / valid / test) | torch.utils.data.Dataset | Chapter 4 (overfitting과 data split) |
| Mini-batch sampling | DataLoader(batch_size, shuffle) | Chapter 4 (SGD) |
| Model | torch.nn.Module | Chapter 2, 6–11 |
| Loss | nn.CrossEntropyLoss, nn.MSELoss | Chapter 3 |
| Optimizer, learning rate | torch.optim.AdamW(model.parameters(), lr) | Chapter 4 |
| Learning rate scheduler | torch.optim.lr_scheduler.CosineAnnealingLR | Chapter 4 |
| Backpropagation | loss.backward() | Chapter 4 |
A.2Custom dataset과 model
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
class ArrayDataset(Dataset):
"""Data를 미리 memory에 올려 두고 index로 꺼낸다."""
def __init__(self, x, y, transform=None):
self.x = torch.as_tensor(x, dtype=torch.float32) # (N, C, H, W)
self.y = torch.as_tensor(y, dtype=torch.long) # (N,)
self.transform = transform
def __len__(self):
return len(self.x)
def __getitem__(self, i):
x = self.x[i]
if self.transform is not None:
x = self.transform(x) # augmentation (Chapter 12)
return x, self.y[i]
class SmallCNN(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.encoder = nn.Sequential(
nn.Conv2d(3, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(),
nn.AdaptiveAvgPool2d(1), nn.Flatten(), # GAP (Chapter 6)
)
self.classifier = nn.Linear(64, num_classes) # logits, softmax는 loss 안에서
def forward(self, x):
return self.classifier(self.encoder(x))
nn.CrossEntropyLoss는 logit을 받아 내부에서 log-softmax를 계산하므로 model 마지막에 softmax를 넣지 않는다. 내부적으로는 $\texttt{CrossEntropyLoss}=\texttt{NLLLoss}\circ\texttt{LogSoftmax}$이다. NLLLoss는 이름과 달리 log를 취하지 않고, 이미 log-probability인 input에서 정답 index의 값을 꺼내 부호를 바꿀 뿐이다. 그래서 확률(softmax output)을 그대로 NLLLoss에 넣으면 $-p_{y}$라는 엉뚱한 값이 나온다. Model이 log-probability를 출력하면 NLLLoss, logit을 출력하면 CrossEntropyLoss를 쓴다.
A.3Training loop
device = "cuda" if torch.cuda.is_available() else "cpu"
model = SmallCNN().to(device) # parameter를 GPU memory로
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.05)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=num_epochs)
train_loader = DataLoader(train_set, batch_size=128, shuffle=True, num_workers=4)
valid_loader = DataLoader(valid_set, batch_size=256, shuffle=False)
best = float("inf")
for epoch in range(num_epochs):
model.train() # Dropout on, BatchNorm은 batch 통계 사용
for x, y in train_loader:
x, y = x.to(device), y.to(device)
logits = model(x) # forward
loss = criterion(logits, y) # NLL
optimizer.zero_grad() # 이전 step의 gradient 제거
loss.backward() # backpropagation
optimizer.step() # parameter update
scheduler.step()
model.eval() # Dropout off, BatchNorm은 running 통계 사용
total, n = 0.0, 0
with torch.no_grad(): # computational graph를 만들지 않음
for x, y in valid_loader:
x, y = x.to(device), y.to(device)
total += criterion(model(x), y).item() * len(y)
n += len(y)
val_loss = total / n
if val_loss < best: # early stopping용 checkpoint
best = val_loss
torch.save(model.state_dict(), "best.pt")
자주 하는 실수는 다음과 같다.
optimizer.zero_grad()를 빼먹으면 PyTorch는 gradient를 누적하므로 이전 batch의 gradient가 더해진다. (의도적으로 누적해 큰 effective batch를 만드는 gradient accumulation도 이 성질을 이용한다.)- Validation에서
model.eval()을 빼먹으면 dropout이 켜지고 BatchNorm이 validation batch 통계로 running average를 오염시킨다. torch.no_grad()없이 inference하면 중간값을 저장하느라 memory를 낭비한다.- Model 전체 대신
state_dict()(parameter 이름과 tensor의 dictionary)를 저장하고, 불러올 때는 같은 class를 만든 뒤load_state_dict한다.model.named_parameters()로 각 parameter의 이름과 shape을 확인할 수 있다.
GPU 여러 개로 학습할 때는 각 GPU가 model 복사본을 들고 서로 다른 mini-batch를 처리한 뒤 gradient를 평균하는 DistributedDataParallel(DDP)을 쓴다. Effective batch size가 GPU 수만큼 커지므로 learning rate를 함께 조정한다.
A.4CPU, RAM, GPU와 data I/O
Python에서 변수를 만들면 RAM에 올라가고, .to("cuda")(또는 .cuda())를 하면 GPU의 VRAM으로 복사된다. 연산은 tensor가 있는 장치에서 일어나며, model과 data가 같은 장치에 있어야 한다. 학습 속도의 병목은 GPU 연산보다 data를 읽어 오는 쪽인 경우가 많다.
Dataset이 매 iteration마다 file 경로에서 image를 읽어 decode하는 것보다, 가능하면 미리 읽어 RAM에 올려 두는 것이 훨씬 빠르다.- PNG나 JPEG는 매번 decode 비용이 든다. 전처리가 끝난 array를
.npy나 tensor로 저장해 두는 것이 좋다. 작은 dataset은 하나의 pickle file로 묶어 두면 관리가 편하다. - Tabular data는 CSV나 Excel이 읽고 쓰기에 느리므로 feather나 parquet 형식을 권한다.
DataLoader의num_workers로 data loading을 병렬화하고,pin_memory=True로 GPU 전송을 빠르게 한다.
A.5개발 환경
처음 시작할 때는 설치 없이 GPU를 쓸 수 있는 Google Colab이 편하다. 연구 단계에서는 원격 GPU server에 SSH로 접속해 code editor(VS Code, 또는 AI 기능이 통합된 Cursor)로 작업하는 경우가 많다. 강의 초반의 Python 실습에서 다룬 도구는 NumPy(배열 연산), pandas(tabular data), Matplotlib(시각화, plt.plot, plt.imshow, subplots), Pillow와 OpenCV(image 읽기, 회전, PIL ↔ NumPy 변환), 그리고 PyTorch이다.
A.6논문 공부법
- 무엇을 읽을까: LLM에게 주제와 관련된 핵심 논문을 찾아 달라고 하거나, "주제 papers github"로 검색하면 누군가 정리해 둔 논문 목록(awesome list)을 찾을 수 있다.
- 읽기 전에: 논문 제목 + "explained"로 YouTube 영상이나 review blog를 먼저 보면 큰 그림을 빠르게 잡을 수 있다.
- 읽으면서: PDF 여백을 넓혀(padding) 손으로 직접 유도와 메모를 적는 것이 가장 효과적이다. 기준은 "5년 뒤에 다시 봐도 바로 기억날 정도로"이다.
- Code와 함께: 공식 구현(GitHub)을 같이 열어 논문의 식이 code의 어디에 대응하는지 확인한다. Shape을 따라가는 것이 가장 빠른 이해 방법이다.
A.7Code 공부의 우선순위
요즘은 model을 처음부터(from scratch) 구현하는 능력이 예전만큼 중요하지 않다. 대부분의 연구는 공개된 pre-trained model을 불러와 adaptation하는 것으로 시작한다(Chapter 12). 그래도 "CIFAR-10으로 image classification model을 직접 설계하고 학습하기"는 한 번 해 볼 만하다. 실무에서 중요한 순서는 대체로 다음과 같다.
- DataLoader: 내 data를 정확히, 빠르게 model에 넣는 부분. 오류가 가장 많이 숨어 있고 결과에 직접 영향을 준다.
- Inference code: 공개 model을 불러와 올바른 전처리로 예측하는 부분.
- Training code: 위의 loop와 checkpoint, logging.
- Model: architecture 자체는 대개 이미 구현된 것을 쓴다.
A.8장별 실습 notebook
본문과 함께 제공되는 notebook 14개는 각 장의 핵심 공식과 정리를 PyTorch로 직접 확인한다. 모두 CPU에서 1분 안에 실행되며, scikit-learn에 포함된 숫자 data나 합성 data만 써서 다운로드가 필요 없다. 정리의 기댓값을 simulation과 비교하거나(03, 12), 직접 구현한 연산이 PyTorch 내장 연산과 같은지 확인하는(02, 05) 식으로, 본문의 유도를 숫자로 검산하는 것이 목적이다.
| Notebook | Chapter | 내용 |
|---|---|---|
01_mle_logistic | 1–3 | Logistic regression MLE(Newton vs PyTorch), softmax–CE gradient, Gaussian MLE = OLS |
02_optimization_backprop | 4 | 손으로 쓴 backprop vs autograd, optimizer 경로, descent lemma |
03_double_descent | 5 | Min-norm risk 정리 검증, random feature double descent, GD → min-norm 해 |
04_cnn_digits | 6, A | 작은 CNN과 이 부록의 training loop |
05_attention | 8–9 | Multi-head attention 구현 검증, causal mask, permutation equivariance |
06_gnn | 11 | GCN node classification, over-smoothing |
07_infonce | 12 | InfoNCE bound와 $\log N$ 상한 |
08_attribution | 13 | Saliency, integrated gradients, Grad-CAM |
09_vae | 15 | VAE, KL closed form vs Monte Carlo, IWAE |
10_diffusion | 17–18 | 2D DDPM 학습, DDPM vs DDIM |
11_flows | 19–20 | RealNVP exact MLE, conditional flow matching |
12_uncertainty_evaluation | 21–22 | ECE, temperature scaling, ensemble, conformal, bootstrap, McNemar |
13_deepsurv | 24 | Partial likelihood로 Cox β 추정, DeepSurv |
14_tiny_gpt_dpo | 26 | Character-level GPT, decoding, DPO loss |
A.9더 공부할 자료
강의에서 추천했던 자료를 주제별로 모았다.
- 3Blue1Brown, Neural Networks series (YouTube): neural network, gradient descent, backpropagation의 시각적 설명. 특히 backpropagation calculus 편.
- 3Blue1Brown, convolution 설명 영상: convolution의 직관.
- Chen et al., "A Simple Framework for Contrastive Learning of Visual Representations" (SimCLR, 2020)와 contrastive learning 해설 글.
- Song & Ermon, "Generative Modeling by Estimating Gradients of the Data Distribution" (2019) 및 저자의 blog post와 강연 영상. 한국어 자료로는 WikiDocs의 diffusion/score model 정리가 참고하기 좋다.
- Ho et al., "Denoising Diffusion Probabilistic Models" (2020); Song, Meng & Ermon, "Denoising Diffusion Implicit Models" (2021); Dhariwal & Nichol, "Diffusion Models Beat GANs on Image Synthesis" (2021); Rombach et al., "High-Resolution Image Synthesis with Latent Diffusion Models" (2022).
- Vaswani et al., "Attention Is All You Need" (2017); Dosovitskiy et al., "An Image is Worth 16x16 Words" (ViT, 2021); Jaegle et al., "Perceiver" (2021); He et al., "Masked Autoencoders Are Scalable Vision Learners" (2022).
- Katzman et al., "DeepSurv" (2018); Lee et al., "DeepHit" (2018).
- Radford et al., GPT-1/2/3 논문(2018–2020); Ouyang et al., "Training language models to follow instructions with human feedback" (InstructGPT, 2022).
Appendix BNotation과 핵심 공식
본문에서 쓰는 기호와, 여러 장에 걸쳐 반복해서 쓰이는 핵심 공식을 한곳에 모았다. 각 공식 옆의 장 번호에 유도와 증명이 있다.
B.1Notation
| Symbol | 의미 |
|---|---|
| $x,\ \bx,\ \bX$ | Scalar, (column) vector, matrix. 문맥상 분명하면 굵은 글씨를 생략한다. |
| $\theta,\ \phi,\ \psi$ | Model parameter(weight). 주로 $\theta$는 model/decoder/generator, $\phi$는 encoder, $\psi$는 discriminator. |
| $f_\theta(\bx)$ | Network가 계산하는 deterministic function |
| $p_\theta(y\mid\bx)$, $p_\theta(\bx)$ | Model이 정의하는 conditional / marginal distribution |
| $p_{\text{data}},\ \hat p_{\text{data}}$ | 실제 data distribution, empirical distribution $\frac1n\sum_i\delta_{\bx_i}$ |
| $\L(\theta)$, $\ell$ | Likelihood 또는 전체 loss, sample 하나의 loss (문맥에 따라) |
| $\E_p[\cdot]$, $\Var$, $\Cov$ | Distribution $p$에 대한 expectation, variance, covariance |
| $H(p)$, $H(p,q)$, $\KL(p\|q)$ | Entropy, cross-entropy, KL divergence |
| $\N(\bmu,\bSigma)$ | Gaussian distribution |
| $\sigma(z)$ | Sigmoid $1/(1+e^{-z})$. Standard deviation도 $\sigma$로 쓰므로 문맥으로 구분한다. |
| $\odot$ | Element-wise (Hadamard) product |
| $\ind[\cdot]$ | Indicator function |
| $\nabla_\bx$, $\nabla_\theta$ | Data에 대한 gradient(score function 등), parameter에 대한 gradient(학습) |
| $B,\ N$ | Batch size |
| $n,\ d_{\text{model}},\ d_k$ | Sequence 길이, Transformer hidden 차원, query/key 차원 |
| $\beta_t,\ \alpha_t,\ \bar\alpha_t$ | Diffusion noise schedule, $\alpha_t=1-\beta_t$, $\bar\alpha_t=\prod_{s\le t}\alpha_s$ |
| $S(t),\ h(t),\ H(t)$ | Survival function, hazard, cumulative hazard (Chapter 24) |
| $\bA,\ \mathbf D,\ \mathcal N(v)$ | Graph의 adjacency matrix, degree matrix, node $v$의 이웃 (Chapter 11) |
B.2Matrix calculus의 layout
Vector와 matrix의 미분은 결과를 어떤 모양으로 배열하느냐(layout)에 따라 transpose가 달라지므로, 식을 읽을 때 convention을 먼저 확인해야 한다. 이 책은 scalar를 vector나 matrix로 미분한 gradient를 원래 변수와 같은 shape으로 둔다(denominator layout과 같은 결과). 예를 들어 $\ell$이 scalar이면 $\partial\ell/\partial\bW$는 $\bW$와 같은 shape이고, 그래서 gradient descent $\bW\leftarrow\bW-\eta\,\partial\ell/\partial\bW$가 성분별로 맞는다. Vector를 vector로 미분한 Jacobian $\partial\by/\partial\bx$는 $\by\in\R^m$, $\bx\in\R^n$일 때 $m\times n$ 행렬(numerator layout)로 쓴다.
| Numerator layout | Denominator layout | |
|---|---|---|
| $\partial y/\partial\bx$ ($y$ scalar, $\bx\in\R^n$) | $1\times n$ row vector | $n\times1$ column vector |
| $\partial\by/\partial x$ ($\by\in\R^m$) | $m\times1$ column vector | $1\times m$ row vector |
| $\partial\by/\partial\bx$ | $m\times n$ | $n\times m$ |
| $\partial y/\partial\bX$ ($\bX\in\R^{p\times q}$) | $q\times p$ | $p\times q$ |
자주 쓰는 결과: $\nabla_\bx(\mathbf a^\top\bx)=\mathbf a$, $\nabla_\bx(\bx^\top\mathbf A\bx)=(\mathbf A+\mathbf A^\top)\bx$, $\nabla_\bW(\mathbf u^\top\bW\mathbf v)=\mathbf u\mathbf v^\top$, $\nabla_\bX\log\det\bX=\bX^{-\top}$.
B.3Likelihood, information, loss
| 내용 | 공식 | Ch. |
|---|---|---|
| MLE | $\hat\theta=\argmax_\theta\sum_i\log p_\theta(\bx_i)$ | 1 |
| Bias–variance | $\mathrm{MSE}=\Var(\hat\theta)+\mathrm{Bias}^2$ | 1 |
| OLS | $\hat\bbeta=(\bX^\top\bX)^{-1}\bX^\top\by$ | 1 |
| MAP와 weight decay | $\theta\sim\N(0,\tau^2\bI)\Rightarrow$ penalty $\|\theta\|^2/(2\tau^2)$ | 1, 4 |
| Cross-entropy 분해 | $H(p,q)=H(p)+\KL(p\|q)$ | 3 |
| MLE = KL 최소화 | $\argmax\E_{p_{\text{data}}}\log p_\theta=\argmin\KL(p_{\text{data}}\|p_\theta)$ | 3 |
| Gaussian KL | $\KL(\N(\bmu,\diag\boldsymbol\sigma^2)\|\N(0,\bI))=\frac12\sum_j(\mu_j^2+\sigma_j^2-\log\sigma_j^2-1)$ | 3, 15 |
| Softmax–CE gradient | $\partial\ell/\partial\bz=\bp-\by$ | 3 |
| Mutual information | $I(X;Y)=H(Y)-H(Y\mid X)=\KL(p_{XY}\|p_Xp_Y)$ | 3, 12 |
B.4Optimization과 architecture
| 내용 | 공식 | Ch. |
|---|---|---|
| Descent lemma | $\L(\theta-\eta\nabla\L)\le\L-\eta(1-\beta\eta/2)\|\nabla\L\|^2$ | 4 |
| Backprop recursion | $\bdelta^{(l)}=(\bW^{(l+1)\top}\bdelta^{(l+1)})\odot g'(\bz^{(l)})$, $\partial\ell/\partial\bW^{(l)}=\bdelta^{(l)}\ba^{(l-1)\top}$ | 4 |
| Adam | $\theta\leftarrow\theta-\eta\,\hat m_t/(\sqrt{\hat v_t}+\epsilon)$, $\hat m_t=m_t/(1-\beta_1^t)$ | 4 |
| He initialization | $\Var(w)=2/n_{\text{in}}$ | 4 |
| Conv output size | $\lfloor(H+2p-k)/s\rfloor+1$, params $C_{\text{out}}(C_{\text{in}}k^2+1)$ | 6 |
| Residual Jacobian | $\partial\bx_{l+1}/\partial\bx_l=\bI+\partial F/\partial\bx_l$ | 6 |
| Attention | $\softmax(\mathbf Q\mathbf K^\top/\sqrt{d_k})\mathbf V$, cost $O(n^2d)$ | 8 |
| Sinusoidal PE | $\mathbf p_{\text{pos},2i}=\sin(\text{pos}/10000^{2i/d})$, $\mathbf p_{\text{pos},2i+1}=\cos(\cdot)$ | 8 |
| ViT token 수 | $N=HW/P^2$ | 9 |
| LoRA | $\bh=\bW_0\bx+\frac{\alpha}{r}\mathbf B\mathbf A\bx$, $\mathbf B_0=\mathbf 0$ | 12 |
| InfoNCE bound | $I(\bx;\bx')\ge\log N-\L_N$ | 12 |
| Grad-CAM | $\alpha_k^c=\frac1Z\sum_{ij}\partial y^c/\partial A^k_{ij}$, $L^c=\mathrm{ReLU}(\sum_k\alpha_k^cA^k)$ | 13 |
| GCN layer | $\bH'=\sigma(\tilde{\mathbf D}^{-1/2}\tilde\bA\tilde{\mathbf D}^{-1/2}\bH\bW)$, $\tilde\bA=\bA+\bI$ | 11 |
| Laplacian quadratic form | $\bx^\top(\mathbf D-\bA)\bx=\sum_{(u,v)\in E}(x_u-x_v)^2$ | 11 |
| Over-smoothing | $\hat\bA^k\bX\to\bu\bu^\top\bX$, $\bu\propto\tilde{\mathbf D}^{1/2}\mathbf 1$ | 11 |
B.5Generative model
| 내용 | 공식 | Ch. |
|---|---|---|
| ELBO | $\log p_\theta(\bx)=\E_q[\log p_\theta(\bx\mid\bz)]-\KL(q\|p(\bz))+\KL(q\|p_\theta(\bz\mid\bx))$ | 15 |
| Reparameterization | $\bz=\bmu_\phi(\bx)+\boldsymbol\sigma_\phi(\bx)\odot\beps$, $\beps\sim\N(0,\bI)$ | 15 |
| Optimal discriminator | $D^\ast=p_{\text{data}}/(p_{\text{data}}+p_g)$, $C(G)=-\log4+2\,\mathrm{JSD}$ | 16 |
| AdaIN | $\sigma(\mathbf y)\frac{\mathbf x-\mu(\mathbf x)}{\sigma(\mathbf x)}+\mu(\mathbf y)$ | 16 |
| Score matching | $J(\theta)=\E[\tr(\nabla_\bx\mathbf s_\theta)+\frac12\|\mathbf s_\theta\|^2]+C$ | 17 |
| Denoising score matching | target $\nabla_{\tilde\bx}\log q_\sigma(\tilde\bx\mid\bx)=-(\tilde\bx-\bx)/\sigma^2$ | 17 |
| Tweedie | $\E[\bx\mid\tilde\bx]=\tilde\bx+\sigma^2\nabla\log q_\sigma(\tilde\bx)$ | 17 |
| Langevin | $\bx\leftarrow\bx+\frac\epsilon2\nabla\log p(\bx)+\sqrt\epsilon\,\bz$ | 17 |
| Forward marginal | $\bx_t=\sqrt{\bar\alpha_t}\bx_0+\sqrt{1-\bar\alpha_t}\beps$ | 18 |
| Forward posterior | $\tilde\beta_t=\frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}\beta_t$, $\tilde\bmu_t=\frac{1}{\sqrt{\alpha_t}}\big(\bx_t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\beps\big)$ | 18 |
| DDPM loss | $\E\|\beps-\beps_\theta(\sqrt{\bar\alpha_t}\bx_0+\sqrt{1-\bar\alpha_t}\beps,t)\|^2$ | 18 |
| ε와 score | $\mathbf s_\theta(\bx_t,t)=-\beps_\theta(\bx_t,t)/\sqrt{1-\bar\alpha_t}$ | 18 |
| Classifier-free guidance | $\tilde\beps=(1+w)\beps_\theta(\bx_t,y)-w\,\beps_\theta(\bx_t,\varnothing)$ | 18 |
| FID | $\|\bmu_r-\bmu_g\|^2+\tr(\bSigma_r+\bSigma_g-2(\bSigma_r\bSigma_g)^{1/2})$ | 18 |
| Change of variables | $\log p_X(\bx)=\log p_Z(f(\bx))+\log|\det\partial f/\partial\bx|$ | 19 |
| Affine coupling | $\bx_B=\bz_B\odot e^{\mathbf s(\bz_A)}+\mathbf t(\bz_A)$, $\log|\det J|=\sum_js_j$ | 19 |
| Instantaneous change of variables | $\frac{\dd}{\dd t}\log p_t(\bz(t))=-\tr(\partial\bv/\partial\bz)$ | 19 |
| VP SDE | $\dd\bx=-\frac12\beta\bx\,\dd t+\sqrt\beta\,\dd\mathbf B_t$, $\bar\alpha(t)=e^{-\int_0^t\beta}$ | 20 |
| Reverse SDE / probability flow ODE | $\dd\bx=[\mathbf f-g^2\nabla\log p_t]\dd t+g\,\dd\bar{\mathbf B}$, $\ \dot\bx=\mathbf f-\frac12g^2\nabla\log p_t$ | 20 |
| Conditional flow matching | $\E\|\bv_\theta((1-t)\bx_0+t\bx_1,t)-(\bx_1-\bx_0)\|^2$ | 20 |
B.6Generalization, uncertainty, evaluation
| 내용 | 공식 | Ch. |
|---|---|---|
| Finite class bound | $|R(f)-\hat R_n(f)|\le\sqrt{(\log|\mathcal F|+\log(2/\delta))/(2n)}$ | 5 |
| Min-norm least squares risk | $\sigma^2\frac{p}{n-p-1}$ ($p\lt n$), $\ r^2(1-\frac np)+\sigma^2\frac{n}{p-n-1}$ ($p>n$) | 5 |
| GD vs ridge filter | $1-(1-\eta s^2)^t$ vs $s^2/(s^2+\lambda)$ | 5 |
| PAC-Bayes | $\E_QR\le\E_Q\hat R_n+\sqrt{(\KL(Q\|P)+\log(2\sqrt n/\delta))/(2n)}$ | 5 |
| NTK dynamics | $\dot{\mathbf u}=-\Theta(\bX,\bX)(\mathbf u-\by)$ | 5 |
| Uncertainty decomposition | $H(\bar\bp)=\E_\theta H(\bp_\theta)+I(y;\theta)$ | 21 |
| Brier score | $\E_{y\sim\bq}\|\bp-\be_y\|^2=\|\bp-\bq\|^2+1-\|\bq\|^2$ | 21 |
| ECE | $\sum_b\frac{|\mathcal B_b|}{n}|\mathrm{acc}(\mathcal B_b)-\mathrm{conf}(\mathcal B_b)|$ | 21 |
| Split conformal | $\hat q=s_{(\lceil(n+1)(1-\alpha)\rceil)}$, coverage $\ge1-\alpha$ | 21 |
| PPV | $\frac{\mathrm{sens}\,\pi}{\mathrm{sens}\,\pi+(1-\mathrm{spec})(1-\pi)}$ | 22 |
| AUC | $P(S_1>S_0)+\frac12P(S_1=S_0)$ | 22 |
| Bayes-optimal threshold | $p(\bx)\ge c_{\text{FP}}/(c_{\text{FP}}+c_{\text{FN}})$ | 22 |
B.7Survival analysis와 LLM
| 내용 | 공식 | Ch. |
|---|---|---|
| Hazard | $h(t)=f(t)/S(t)=-\frac{\dd}{\dd t}\log S(t)$, $S=e^{-H}$ | 24 |
| Kaplan–Meier | $\hat S(t)=\prod_{t_{(j)}\le t}(1-d_j/n_j)$ | 24 |
| Cox partial likelihood | $\prod_{i:\delta_i=1}\frac{e^{\bx_i^\top\bbeta}}{\sum_{j\in R(Y_i)}e^{\bx_j^\top\bbeta}}$ | 24 |
| Perplexity | $\exp\big(-\frac1n\sum_t\log p_\theta(x_t\mid x_{\lt t})\big)$ | 26 |
| Bradley–Terry reward loss | $-\log\sigma(r(x,y_w)-r(x,y_l))$ | 26 |
| KL-regularized optimum | $\pi^\ast\propto\pi_{\text{ref}}\exp(r/\beta)$ | 26 |
| DPO | $-\log\sigma\big(\beta\log\frac{\pi_\theta(y_w)}{\pi_{\text{ref}}(y_w)}-\beta\log\frac{\pi_\theta(y_l)}{\pi_{\text{ref}}(y_l)}\big)$ | 26 |
B.8Reinforcement learning, efficiency, routing
| 내용 | 공식 | Ch. |
|---|---|---|
| Policy gradient | $\nabla J=\E\big[\sum_t\nabla\log\pi_\theta(a_t\mid s_t)\,(G_t-b(s_t))\big]$ | 25 |
| Optimal scalar baseline | $b^\ast=\E[s^2G]/\E[s^2]$, $s=\partial\log\pi$ | 25 |
| TD error, GAE | $\delta_t=r_t+\gamma V(s_{t+1})-V(s_t)$, $\hat A_t=\sum_l(\gamma\lambda)^l\delta_{t+l}$ | 25 |
| Performance difference | $J(\pi')-J(\pi)=\E_{\pi'}\big[\sum_t\gamma^tA^\pi(s_t,a_t)\big]$ | 25 |
| PPO | $\E\big[\min(\rho\hat A,\mathrm{clip}(\rho,1\pm\epsilon)\hat A)\big]$ | 25 |
| RLOO / GRPO advantage | $r_i-\frac1{G-1}\sum_{j\ne i}r_j$, $\ (r_i-\bar r)/\mathrm{std}(r)$ | 25 |
| Rounding error | $\E(x-\hat x)^2=s^2/12$, $s=\alpha/(2^{b-1}-1)$ | 29 |
| SmoothQuant | $\bX\bW=(\bX\diag(\mathbf c)^{-1})(\diag(\mathbf c)\bW)$ | 29 |
| OBS / GPTQ update | $\delta\bw=-\frac{w_q-\mathrm{quant}(w_q)}{[\mathbf H^{-1}]_{qq}}\mathbf H^{-1}\mathbf e_q$ | 29 |
| Quantized small update | $\E[q(w+\Delta)-q(w)]=\Delta$, $\Var=s^2f(1-f)$ | 29 |
| MoE gate gradient | $\partial\log p/\partial u_k=h_k-g_k$ | 30 |
| Load balancing loss | $\alpha N\sum_if_iP_i$ | 30 |
| Bayes-optimal router | $r^\ast(\bx)=\argmax_k\eta_k(\bx)$, $\mathrm{Acc}=\E\max_k\eta_k(X)$ | 30 |
| Speculative sampling | accept w.p. $\min(1,p/q)$, else $\propto(p-q)_+$; acceptance $1-\mathrm{TV}(p,q)$ | 30 |
B.9Long sequence, imperfect labels, shift, scale
| 내용 | 공식 | Ch. |
|---|---|---|
| RoPE | $(\mathbf R_m\bq)^\top(\mathbf R_n\bk)=\bq^\top\mathbf R_{n-m}\bk$ | 10 |
| Online softmax | $\ell=e^{m_1-m}\ell_1+e^{m_2-m}\ell_2$, $m=\max(m_1,m_2)$ | 10 |
| SSM (ZOH) | $\mathbf h_k=e^{\Delta\bA}\mathbf h_{k-1}+\bar\bB u_k$, $y=\bar{\mathbf K}*u$, $\bar{\mathbf K}_j=\mathbf C\bar\bA^j\bar\bB$ | 10 |
| Forward correction | $-\log(\mathbf T^\top\bp_\theta(\bx))_{\tilde y}$, $T_{ij}=P(\tilde y=j\mid y=i)$ | 14 |
| Logit adjustment | $\argmax_y f_y(\bx)-\tau\log\pi_y$ | 14 |
| Importance weight | $R_T=\E_S[w\ell]$, $w=\frac{n_S}{n_T}\frac{c(\bx)}{1-c(\bx)}$, $n_{\text{eff}}=(\sum w)^2/\sum w^2$ | 23 |
| Label shift correction | $p_T(y\mid\bx)\propto p_S(y\mid\bx)\pi^T_y/\pi^S_y$; BBSE $\boldsymbol\mu_T=\mathbf C\boldsymbol\pi^T$ | 23 |
| Ben-David bound | $\varepsilon_T\le\varepsilon_S+\frac12d_{\mathcal H\Delta\mathcal H}+\lambda^\ast$ | 23 |
| Ring all-reduce | GPU당 전송량 $2(N-1)M/N$ | 28 |
| ZeRO memory | $16\Psi$ → $4\Psi+12\Psi/N$ → $2\Psi+14\Psi/N$ → $16\Psi/N$ | 28 |
| Pipeline bubble | $(p-1)/(m+p-1)$ | 28 |
| Gradient noise scale | $B_{\text{noise}}=\tr(\bSigma)/\|\bG\|^2$ | 28 |
Appendix C참고문헌
본문에서 인용한 주요 논문을 Part별로 모았다. 대부분 arXiv에 공개되어 있으며 링크는 arXiv abstract 페이지(일부는 학술지 페이지)로 연결된다. 출판 연도는 학회·학술지 기준이다.
C.1Part I · Foundations (Ch. 1–5)
- Kingma, D. P. & Ba, J. (2015). Adam: A Method for Stochastic Optimization. arXiv:1412.6980
- Loshchilov, I. & Hutter, F. (2019). Decoupled Weight Decay Regularization. arXiv:1711.05101
- He, K. et al. (2015). Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification. arXiv:1502.01852
- Ioffe, S. & Szegedy, C. (2015). Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift. arXiv:1502.03167
- Ba, J. L., Kiros, J. R. & Hinton, G. E. (2016). Layer Normalization. arXiv:1607.06450
- Srivastava, N. et al. (2014). Dropout: A Simple Way to Prevent Neural Networks from Overfitting. JMLR
- Zhang, C. et al. (2017). Understanding Deep Learning Requires Rethinking Generalization. arXiv:1611.03530
- Belkin, M. et al. (2019). Reconciling Modern Machine Learning Practice and the Bias-Variance Trade-off. arXiv:1812.11118
- Nakkiran, P. et al. (2020). Deep Double Descent: Where Bigger Models and More Data Hurt. arXiv:1912.02292
- Nakkiran, P. et al. (2021). Optimal Regularization Can Mitigate Double Descent. arXiv:2003.01897
- Hastie, T., Montanari, A., Rosset, S. & Tibshirani, R. J. (2022). Surprises in High-Dimensional Ridgeless Least Squares Interpolation. arXiv:1903.08560
- Bartlett, P. L. et al. (2020). Benign Overfitting in Linear Regression. arXiv:1906.11300
- Soudry, D. et al. (2018). The Implicit Bias of Gradient Descent on Separable Data. arXiv:1710.10345
- Keskar, N. S. et al. (2017). On Large-Batch Training for Deep Learning: Generalization Gap and Sharp Minima. arXiv:1609.04836
- Dinh, L. et al. (2017). Sharp Minima Can Generalize For Deep Nets. arXiv:1703.04933
- Goyal, P. et al. (2017). Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour. arXiv:1706.02677
- Cohen, J. M. et al. (2021). Gradient Descent on Neural Networks Typically Occurs at the Edge of Stability. arXiv:2103.00065
- Foret, P. et al. (2021). Sharpness-Aware Minimization for Efficiently Improving Generalization. arXiv:2010.01412
- Dziugaite, G. K. & Roy, D. M. (2017). Computing Nonvacuous Generalization Bounds for Deep (Stochastic) Neural Networks with Many More Parameters than Training Data. arXiv:1703.11008
- Jacot, A., Gabriel, F. & Hongler, C. (2018). Neural Tangent Kernel: Convergence and Generalization in Neural Networks. arXiv:1806.07572
- Chizat, L., Oyallon, E. & Bach, F. (2019). On Lazy Training in Differentiable Programming. arXiv:1812.07956
C.2Part II · Architectures (Ch. 6–11)
- He, K. et al. (2016). Deep Residual Learning for Image Recognition. arXiv:1512.03385
- Simonyan, K. & Zisserman, A. (2015). Very Deep Convolutional Networks for Large-Scale Image Recognition. arXiv:1409.1556
- Ronneberger, O., Fischer, P. & Brox, T. (2015). U-Net: Convolutional Networks for Biomedical Image Segmentation. arXiv:1505.04597
- Mikolov, T. et al. (2013). Efficient Estimation of Word Representations in Vector Space. arXiv:1301.3781
- Mikolov, T. et al. (2013). Distributed Representations of Words and Phrases and their Compositionality. arXiv:1310.4546
- Hochreiter, S. & Schmidhuber, J. (1997). Long Short-Term Memory. DOI
- Cho, K. et al. (2014). Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation. arXiv:1406.1078
- Bahdanau, D., Cho, K. & Bengio, Y. (2015). Neural Machine Translation by Jointly Learning to Align and Translate. arXiv:1409.0473
- Vaswani, A. et al. (2017). Attention Is All You Need. arXiv:1706.03762
- Dosovitskiy, A. et al. (2021). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. arXiv:2010.11929
- Touvron, H. et al. (2021). Training Data-Efficient Image Transformers & Distillation through Attention. arXiv:2012.12877
- Jaegle, A. et al. (2021). Perceiver: General Perception with Iterative Attention. arXiv:2103.03206
- Shazeer, N. (2019). Fast Transformer Decoding: One Write-Head is All You Need. arXiv:1911.02150
- Ainslie, J. et al. (2023). GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints. arXiv:2305.13245
- Su, J. et al. (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding. arXiv:2104.09864
- Chen, S. et al. (2023). Extending Context Window of Large Language Models via Positional Interpolation. arXiv:2306.15595
- Peng, B. et al. (2023). YaRN: Efficient Context Window Extension of Large Language Models. arXiv:2309.00071
- Milakov, M. & Gimelshein, N. (2018). Online Normalizer Calculation for Softmax. arXiv:1805.02867
- Dao, T. et al. (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. arXiv:2205.14135
- Beltagy, I., Peters, M. E. & Cohan, A. (2020). Longformer: The Long-Document Transformer. arXiv:2004.05150
- Katharopoulos, A. et al. (2020). Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention. arXiv:2006.16236
- Tay, Y. et al. (2021). Long Range Arena: A Benchmark for Efficient Transformers. arXiv:2011.04006
- Gu, A. et al. (2020). HiPPO: Recurrent Memory with Optimal Polynomial Projections. arXiv:2008.07669
- Gu, A., Goel, K. & Ré, C. (2022). Efficiently Modeling Long Sequences with Structured State Spaces. arXiv:2111.00396
- Gu, A. et al. (2022). On the Parameterization and Initialization of Diagonal State Space Models. arXiv:2206.11893
- Gu, A. & Dao, T. (2023). Mamba: Linear-Time Sequence Modeling with Selective State Spaces. arXiv:2312.00752
- Dao, T. & Gu, A. (2024). Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality. arXiv:2405.21060
- Lieber, O. et al. (2024). Jamba: A Hybrid Transformer-Mamba Language Model. arXiv:2403.19887
- Bruna, J. et al. (2014). Spectral Networks and Locally Connected Networks on Graphs. arXiv:1312.6203
- Defferrard, M., Bresson, X. & Vandergheynst, P. (2016). Convolutional Neural Networks on Graphs with Fast Localized Spectral Filtering. arXiv:1606.09375
- Kipf, T. N. & Welling, M. (2017). Semi-Supervised Classification with Graph Convolutional Networks. arXiv:1609.02907
- Gilmer, J. et al. (2017). Neural Message Passing for Quantum Chemistry. arXiv:1704.01212
- Hamilton, W. L., Ying, R. & Leskovec, J. (2017). Inductive Representation Learning on Large Graphs. arXiv:1706.02216
- Veličković, P. et al. (2018). Graph Attention Networks. arXiv:1710.10903
- Xu, K. et al. (2019). How Powerful are Graph Neural Networks?. arXiv:1810.00826
- Morris, C. et al. (2019). Weisfeiler and Leman Go Neural: Higher-order Graph Neural Networks. arXiv:1810.02244
- Oono, K. & Suzuki, T. (2020). Graph Neural Networks Exponentially Lose Expressive Power for Node Classification. arXiv:1905.10947
- Alon, U. & Yahav, E. (2021). On the Bottleneck of Graph Neural Networks and its Practical Implications. arXiv:2006.05205
- Satorras, V. G., Hoogeboom, E. & Welling, M. (2021). E(n) Equivariant Graph Neural Networks. arXiv:2102.09844
C.3Part III · Representation Learning (Ch. 12–14)
- van den Oord, A., Li, Y. & Vinyals, O. (2018). Representation Learning with Contrastive Predictive Coding. arXiv:1807.03748
- Poole, B. et al. (2019). On Variational Bounds of Mutual Information. arXiv:1905.06922
- Chen, T. et al. (2020). A Simple Framework for Contrastive Learning of Visual Representations. arXiv:2002.05709
- He, K. et al. (2020). Momentum Contrast for Unsupervised Visual Representation Learning. arXiv:1911.05722
- Khosla, P. et al. (2020). Supervised Contrastive Learning. arXiv:2004.11362
- Wang, T. & Isola, P. (2020). Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere. arXiv:2005.10242
- Grill, J.-B. et al. (2020). Bootstrap Your Own Latent: A New Approach to Self-Supervised Learning. arXiv:2006.07733
- Chen, X. & He, K. (2021). Exploring Simple Siamese Representation Learning. arXiv:2011.10566
- Tian, Y., Chen, X. & Ganguli, S. (2021). Understanding Self-supervised Learning Dynamics without Contrastive Pairs. arXiv:2102.06810
- Zbontar, J. et al. (2021). Barlow Twins: Self-Supervised Learning via Redundancy Reduction. arXiv:2103.03230
- Bardes, A., Ponce, J. & LeCun, Y. (2022). VICReg: Variance-Invariance-Covariance Regularization for Self-Supervised Learning. arXiv:2105.04906
- Caron, M. et al. (2021). Emerging Properties in Self-Supervised Vision Transformers. arXiv:2104.14294
- Oquab, M. et al. (2024). DINOv2: Learning Robust Visual Features without Supervision. arXiv:2304.07193
- Assran, M. et al. (2023). Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture. arXiv:2301.08243
- He, K. et al. (2022). Masked Autoencoders Are Scalable Vision Learners. arXiv:2111.06377
- Devlin, J. et al. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. arXiv:1810.04805
- Radford, A. et al. (2021). Learning Transferable Visual Models From Natural Language Supervision. arXiv:2103.00020
- Hu, E. J. et al. (2022). LoRA: Low-Rank Adaptation of Large Language Models. arXiv:2106.09685
- Hinton, G., Vinyals, O. & Dean, J. (2015). Distilling the Knowledge in a Neural Network. arXiv:1503.02531
- Tarvainen, A. & Valpola, H. (2017). Mean Teachers are Better Role Models: Weight-Averaged Consistency Targets Improve Semi-Supervised Deep Learning Results. arXiv:1703.01780
- Sohn, K. et al. (2020). FixMatch: Simplifying Semi-Supervised Learning with Consistency and Confidence. arXiv:2001.07685
- Northcutt, C. G., Athalye, A. & Mueller, J. (2021). Pervasive Label Errors in Test Sets Destabilize Machine Learning Benchmarks. arXiv:2103.14749
- Patrini, G. et al. (2017). Making Deep Neural Networks Robust to Label Noise: a Loss Correction Approach. arXiv:1609.03683
- Ghosh, A., Kumar, H. & Sastry, P. S. (2017). Robust Loss Functions under Label Noise for Deep Neural Networks. arXiv:1712.09482
- Zhang, Z. & Sabuncu, M. R. (2018). Generalized Cross Entropy Loss for Training Deep Neural Networks with Noisy Labels. arXiv:1805.07836
- Arpit, D. et al. (2017). A Closer Look at Memorization in Deep Networks. arXiv:1706.05394
- Han, B. et al. (2018). Co-teaching: Robust Training of Deep Neural Networks with Extremely Noisy Labels. arXiv:1804.06872
- Menon, A. K. et al. (2021). Long-tail Learning via Logit Adjustment. arXiv:2007.07314
- Lin, T.-Y. et al. (2017). Focal Loss for Dense Object Detection. arXiv:1708.02002
- Houlsby, N. et al. (2011). Bayesian Active Learning for Classification and Preference Learning. arXiv:1112.5745
- Gal, Y., Islam, R. & Ghahramani, Z. (2017). Deep Bayesian Active Learning with Image Data. arXiv:1703.02910
- Sener, O. & Savarese, S. (2018). Active Learning for Convolutional Neural Networks: A Core-Set Approach. arXiv:1708.00489
- Simonyan, K., Vedaldi, A. & Zisserman, A. (2014). Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps. arXiv:1312.6034
- Zeiler, M. D. & Fergus, R. (2014). Visualizing and Understanding Convolutional Networks. arXiv:1311.2901
- Springenberg, J. T. et al. (2015). Striving for Simplicity: The All Convolutional Net. arXiv:1412.6806
- Zhou, B. et al. (2016). Learning Deep Features for Discriminative Localization. arXiv:1512.04150
- Selvaraju, R. R. et al. (2017). Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization. arXiv:1610.02391
- Sundararajan, M., Taly, A. & Yan, Q. (2017). Axiomatic Attribution for Deep Networks. arXiv:1703.01365
- Adebayo, J. et al. (2018). Sanity Checks for Saliency Maps. arXiv:1810.03292
- Wei, J. et al. (2022). Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. arXiv:2201.11903
C.4Part IV · Generative Models (Ch. 15–20)
- Kingma, D. P. & Welling, M. (2014). Auto-Encoding Variational Bayes. arXiv:1312.6114
- Burda, Y., Grosse, R. & Salakhutdinov, R. (2016). Importance Weighted Autoencoders. arXiv:1509.00519
- Goodfellow, I. et al. (2014). Generative Adversarial Nets. arXiv:1406.2661
- Mirza, M. & Osindero, S. (2014). Conditional Generative Adversarial Nets. arXiv:1411.1784
- Huszár, F. (2015). How (not) to Train your Generative Model: Scheduled Sampling, Likelihood, Adversary?. arXiv:1511.05101
- Arjovsky, M. & Bottou, L. (2017). Towards Principled Methods for Training Generative Adversarial Networks. arXiv:1701.04862
- Arjovsky, M., Chintala, S. & Bottou, L. (2017). Wasserstein GAN. arXiv:1701.07875
- Gulrajani, I. et al. (2017). Improved Training of Wasserstein GANs. arXiv:1704.00028
- Isola, P. et al. (2017). Image-to-Image Translation with Conditional Adversarial Networks. arXiv:1611.07004
- Gatys, L. A., Ecker, A. S. & Bethge, M. (2015). A Neural Algorithm of Artistic Style. arXiv:1508.06576
- Huang, X. & Belongie, S. (2017). Arbitrary Style Transfer in Real-time with Adaptive Instance Normalization. arXiv:1703.06868
- Karras, T., Laine, S. & Aila, T. (2019). A Style-Based Generator Architecture for Generative Adversarial Networks. arXiv:1812.04948
- Hyvärinen, A. (2005). Estimation of Non-Normalized Statistical Models by Score Matching. JMLR
- Song, Y. & Ermon, S. (2019). Generative Modeling by Estimating Gradients of the Data Distribution. arXiv:1907.05600
- Song, Y. et al. (2019). Sliced Score Matching: A Scalable Approach to Density and Score Estimation. arXiv:1905.07088
- Ho, J., Jain, A. & Abbeel, P. (2020). Denoising Diffusion Probabilistic Models. arXiv:2006.11239
- Song, J., Meng, C. & Ermon, S. (2021). Denoising Diffusion Implicit Models. arXiv:2010.02502
- Dhariwal, P. & Nichol, A. (2021). Diffusion Models Beat GANs on Image Synthesis. arXiv:2105.05233
- Ho, J. & Salimans, T. (2022). Classifier-Free Diffusion Guidance. arXiv:2207.12598
- Rombach, R. et al. (2022). High-Resolution Image Synthesis with Latent Diffusion Models. arXiv:2112.10752
- Salimans, T. et al. (2016). Improved Techniques for Training GANs. arXiv:1606.03498
- Heusel, M. et al. (2017). GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium. arXiv:1706.08500
- Zhang, R. et al. (2018). The Unreasonable Effectiveness of Deep Features as a Perceptual Metric. arXiv:1801.03924
- Dinh, L., Krueger, D. & Bengio, Y. (2015). NICE: Non-linear Independent Components Estimation. arXiv:1410.8516
- Dinh, L., Sohl-Dickstein, J. & Bengio, S. (2017). Density Estimation using Real NVP. arXiv:1605.08803
- Kingma, D. P. & Dhariwal, P. (2018). Glow: Generative Flow with Invertible 1x1 Convolutions. arXiv:1807.03039
- Germain, M. et al. (2015). MADE: Masked Autoencoder for Distribution Estimation. arXiv:1502.03509
- Papamakarios, G., Pavlakou, T. & Murray, I. (2017). Masked Autoregressive Flow for Density Estimation. arXiv:1705.07057
- Kingma, D. P. et al. (2016). Improving Variational Inference with Inverse Autoregressive Flow. arXiv:1606.04934
- Theis, L., van den Oord, A. & Bethge, M. (2016). A Note on the Evaluation of Generative Models. arXiv:1511.01844
- Chen, R. T. Q. et al. (2018). Neural Ordinary Differential Equations. arXiv:1806.07366
- Grathwohl, W. et al. (2019). FFJORD: Free-form Continuous Dynamics for Scalable Reversible Generative Models. arXiv:1810.01367
- Nalisnick, E. et al. (2019). Do Deep Generative Models Know What They Don't Know?. arXiv:1810.09136
- Song, Y. et al. (2021). Score-Based Generative Modeling through Stochastic Differential Equations. arXiv:2011.13456
- Karras, T. et al. (2022). Elucidating the Design Space of Diffusion-Based Generative Models. arXiv:2206.00364
- Lu, C. et al. (2022). DPM-Solver: A Fast ODE Solver for Diffusion Probabilistic Model Sampling in Around 10 Steps. arXiv:2206.00927
- Lipman, Y. et al. (2023). Flow Matching for Generative Modeling. arXiv:2210.02747
- Liu, X., Gong, C. & Liu, Q. (2023). Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow. arXiv:2209.03003
- Albergo, M. S. & Vanden-Eijnden, E. (2023). Building Normalizing Flows with Stochastic Interpolants. arXiv:2209.15571
- Song, Y. et al. (2023). Consistency Models. arXiv:2303.01469
- Esser, P. et al. (2024). Scaling Rectified Flow Transformers for High-Resolution Image Synthesis. arXiv:2403.03206
C.5Part V · Uncertainty와 Evaluation (Ch. 21–23)
- Guo, C. et al. (2017). On Calibration of Modern Neural Networks. arXiv:1706.04599
- Blundell, C. et al. (2015). Weight Uncertainty in Neural Networks. arXiv:1505.05424
- Gal, Y. & Ghahramani, Z. (2016). Dropout as a Bayesian Approximation: Representing Model Uncertainty in Deep Learning. arXiv:1506.02142
- Lakshminarayanan, B., Pritzel, A. & Blundell, C. (2017). Simple and Scalable Predictive Uncertainty Estimation using Deep Ensembles. arXiv:1612.01474
- Fort, S., Hu, H. & Lakshminarayanan, B. (2019). Deep Ensembles: A Loss Landscape Perspective. arXiv:1912.02757
- Maddox, W. J. et al. (2019). A Simple Baseline for Bayesian Uncertainty in Deep Learning. arXiv:1902.02476
- Daxberger, E. et al. (2021). Laplace Redux – Effortless Bayesian Deep Learning. arXiv:2106.14806
- Ovadia, Y. et al. (2019). Can You Trust Your Model's Uncertainty? Evaluating Predictive Uncertainty Under Dataset Shift. arXiv:1906.02530
- Seitzer, M. et al. (2022). On the Pitfalls of Heteroscedastic Uncertainty Estimation with Probabilistic Neural Networks. arXiv:2203.09168
- Romano, Y., Patterson, E. & Candès, E. (2019). Conformalized Quantile Regression. arXiv:1905.03222
- Angelopoulos, A. N. & Bates, S. (2023). A Gentle Introduction to Conformal Prediction and Distribution-Free Uncertainty Quantification. arXiv:2107.07511
- Hendrycks, D. & Gimpel, K. (2017). A Baseline for Detecting Misclassified and Out-of-Distribution Examples in Neural Networks. arXiv:1610.02136
- Shimodaira, H. (2000). Improving Predictive Inference under Covariate Shift by Weighting the Log-Likelihood Function. DOI
- Saerens, M., Latinne, P. & Decaestecker, C. (2002). Adjusting the Outputs of a Classifier to New a Priori Probabilities: A Simple Procedure. DOI
- Lipton, Z. C., Wang, Y.-X. & Smola, A. (2018). Detecting and Correcting for Label Shift with Black Box Predictors. arXiv:1802.03916
- Ben-David, S. et al. (2010). A Theory of Learning from Different Domains. DOI
- Ganin, Y. et al. (2016). Domain-Adversarial Training of Neural Networks. arXiv:1505.07818
- Zhao, H. et al. (2019). On Learning Invariant Representations for Domain Adaptation. arXiv:1901.09453
- Li, Y. et al. (2018). Revisiting Batch Normalization For Practical Domain Adaptation. arXiv:1603.04779
- Wang, D. et al. (2021). Tent: Fully Test-time Adaptation by Entropy Minimization. arXiv:2006.10726
- Gretton, A. et al. (2012). A Kernel Two-Sample Test. JMLR
- Lopez-Paz, D. & Oquab, M. (2017). Revisiting Classifier Two-Sample Tests. arXiv:1610.06545
- Rabanser, S., Günnemann, S. & Lipton, Z. C. (2019). Failing Loudly: An Empirical Study of Methods for Detecting Dataset Shift. arXiv:1810.11953
- Arjovsky, M. et al. (2019). Invariant Risk Minimization. arXiv:1907.02893
- Sagawa, S. et al. (2020). Distributionally Robust Neural Networks for Group Shifts: On the Importance of Regularization for Worst-Case Generalization. arXiv:1911.08731
- Koh, P. W. et al. (2021). WILDS: A Benchmark of in-the-Wild Distribution Shifts. arXiv:2012.07421
- Recht, B. et al. (2019). Do ImageNet Classifiers Generalize to ImageNet?. arXiv:1902.10811
- Bates, S., Hastie, T. & Tibshirani, R. (2023). Cross-validation: What Does It Estimate and How Well Does It Do It?. arXiv:2104.00673
- Bouthillier, X. et al. (2021). Accounting for Variance in Machine Learning Benchmarks. arXiv:2103.03098
C.6Part VI · Extensions (Ch. 24–27)
- Katzman, J. L. et al. (2018). DeepSurv: Personalized Treatment Recommender System Using a Cox Proportional Hazards Deep Neural Network. arXiv:1606.00931
- Lee, C. et al. (2018). DeepHit: A Deep Learning Approach to Survival Analysis with Competing Risks. DOI
- Williams, R. J. (1992). Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning. DOI
- Mnih, V. et al. (2015). Human-level Control through Deep Reinforcement Learning. DOI
- Schulman, J. et al. (2015). Trust Region Policy Optimization. arXiv:1502.05477
- Schulman, J. et al. (2016). High-Dimensional Continuous Control Using Generalized Advantage Estimation. arXiv:1506.02438
- Shao, Z. et al. (2024). DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models. arXiv:2402.03300
- Ahmadian, A. et al. (2024). Back to Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs. arXiv:2402.14740
- DeepSeek-AI (2025). DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning. arXiv:2501.12948
- Liu, Z. et al. (2025). Understanding R1-Zero-Like Training: A Critical Perspective. arXiv:2503.20783
- Sennrich, R., Haddow, B. & Birch, A. (2016). Neural Machine Translation of Rare Words with Subword Units. arXiv:1508.07909
- Brown, T. B. et al. (2020). Language Models are Few-Shot Learners. arXiv:2005.14165
- Kaplan, J. et al. (2020). Scaling Laws for Neural Language Models. arXiv:2001.08361
- Hoffmann, J. et al. (2022). Training Compute-Optimal Large Language Models. arXiv:2203.15556
- Ouyang, L. et al. (2022). Training Language Models to Follow Instructions with Human Feedback. arXiv:2203.02155
- Schulman, J. et al. (2017). Proximal Policy Optimization Algorithms. arXiv:1707.06347
- Rafailov, R. et al. (2023). Direct Preference Optimization: Your Language Model is Secretly a Reward Model. arXiv:2305.18290
- Alayrac, J.-B. et al. (2022). Flamingo: a Visual Language Model for Few-Shot Learning. arXiv:2204.14198
- Li, J. et al. (2023). BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models. arXiv:2301.12597
- Liu, H. et al. (2023). Visual Instruction Tuning. arXiv:2304.08485
- Liu, H. et al. (2024). Improved Baselines with Visual Instruction Tuning. arXiv:2310.03744
- Chameleon Team (2024). Chameleon: Mixed-Modal Early-Fusion Foundation Models. arXiv:2405.09818
- Radford, A. et al. (2023). Robust Speech Recognition via Large-Scale Weak Supervision. arXiv:2212.04356
- Rohrbach, A. et al. (2018). Object Hallucination in Image Captioning. arXiv:1809.02156
- Li, Y. et al. (2023). Evaluating Object Hallucination in Large Vision-Language Models. arXiv:2305.10355
- Leng, S. et al. (2024). Mitigating Object Hallucinations in Large Vision-Language Models through Visual Contrastive Decoding. arXiv:2311.16922
C.7Part VII · Efficiency와 Routing (Ch. 28–30)
- Li, S. et al. (2020). PyTorch Distributed: Experiences on Accelerating Data Parallel Training. arXiv:2006.15704
- Zhao, Y. et al. (2023). PyTorch FSDP: Experiences on Scaling Fully Sharded Data Parallel. arXiv:2304.11277
- Shoeybi, M. et al. (2019). Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism. arXiv:1909.08053
- Huang, Y. et al. (2019). GPipe: Efficient Training of Giant Neural Networks using Pipeline Parallelism. arXiv:1811.06965
- Harlap, A. et al. (2018). PipeDream: Fast and Efficient Pipeline Parallel DNN Training. arXiv:1806.03377
- Chen, T. et al. (2016). Training Deep Nets with Sublinear Memory Cost. arXiv:1604.06174
- You, Y., Gitman, I. & Ginsburg, B. (2017). Large Batch Training of Convolutional Networks. arXiv:1708.03888
- You, Y. et al. (2020). Large Batch Optimization for Deep Learning: Training BERT in 76 minutes. arXiv:1904.00962
- McCandlish, S. et al. (2018). An Empirical Model of Large-Batch Training. arXiv:1812.06162
- Micikevicius, P. et al. (2018). Mixed Precision Training. arXiv:1710.03740
- Rajbhandari, S. et al. (2020). ZeRO: Memory Optimizations Toward Training Trillion Parameter Models. arXiv:1910.02054
- Aghajanyan, A., Zettlemoyer, L. & Gupta, S. (2021). Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning. arXiv:2012.13255
- Houlsby, N. et al. (2019). Parameter-Efficient Transfer Learning for NLP. arXiv:1902.00751
- Li, X. L. & Liang, P. (2021). Prefix-Tuning: Optimizing Continuous Prompts for Generation. arXiv:2101.00190
- Lester, B., Al-Rfou, R. & Constant, N. (2021). The Power of Scale for Parameter-Efficient Prompt Tuning. arXiv:2104.08691
- Ben Zaken, E., Ravfogel, S. & Goldberg, Y. (2022). BitFit: Simple Parameter-efficient Fine-tuning for Transformer-based Masked Language-models. arXiv:2106.10199
- Kalajdzievski, D. (2023). A Rank Stabilization Scaling Factor for Fine-Tuning with LoRA. arXiv:2312.03732
- Liu, S.-Y. et al. (2024). DoRA: Weight-Decomposed Low-Rank Adaptation. arXiv:2402.09353
- Banner, R., Nahshan, Y. & Soudry, D. (2019). Post-training 4-bit Quantization of Convolution Networks for Rapid-Deployment. arXiv:1810.05723
- Dettmers, T. et al. (2022). LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale. arXiv:2208.07339
- Xiao, G. et al. (2023). SmoothQuant: Accurate and Efficient Post-Training Quantization for Large Language Models. arXiv:2211.10438
- Lin, J. et al. (2024). AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration. arXiv:2306.00978
- Frantar, E. et al. (2023). GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers. arXiv:2210.17323
- Bengio, Y., Léonard, N. & Courville, A. (2013). Estimating or Propagating Gradients Through Stochastic Neurons for Conditional Computation. arXiv:1308.3432
- Esser, S. K. et al. (2020). Learned Step Size Quantization. arXiv:1902.08153
- Dettmers, T. et al. (2023). QLoRA: Efficient Finetuning of Quantized LLMs. arXiv:2305.14314
- Li, Y. et al. (2024). LoftQ: LoRA-Fine-Tuning-Aware Quantization for Large Language Models. arXiv:2310.08659
- Frankle, J. & Carbin, M. (2019). The Lottery Ticket Hypothesis: Finding Sparse, Trainable Neural Networks. arXiv:1803.03635
- Frantar, E. & Alistarh, D. (2023). SparseGPT: Massive Language Models Can Be Accurately Pruned in One-Shot. arXiv:2301.00774
- Jacobs, R. A. et al. (1991). Adaptive Mixtures of Local Experts. DOI
- Shazeer, N. et al. (2017). Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer. arXiv:1701.06538
- Fedus, W., Zoph, B. & Shazeer, N. (2022). Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity. arXiv:2101.03961
- Zoph, B. et al. (2022). ST-MoE: Designing Stable and Transferable Sparse Expert Models. arXiv:2202.08906
- Zhou, Y. et al. (2022). Mixture-of-Experts with Expert Choice Routing. arXiv:2202.09368
- Jiang, A. Q. et al. (2024). Mixtral of Experts. arXiv:2401.04088
- Dai, D. et al. (2024). DeepSeekMoE: Towards Ultimate Expert Specialization in Mixture-of-Experts Language Models. arXiv:2401.06066
- Wang, L. et al. (2024). Auxiliary-Loss-Free Load Balancing Strategy for Mixture-of-Experts. arXiv:2408.15664
- DeepSeek-AI (2024). DeepSeek-V3 Technical Report. arXiv:2412.19437
- Cruz, R. M. O., Sabourin, R. & Cavalcanti, G. D. C. (2018). Dynamic Classifier Selection: Recent Advances and Perspectives. DOI
- Madras, D., Pitassi, T. & Zemel, R. (2018). Predict Responsibly: Improving Fairness and Accuracy by Learning to Defer. arXiv:1711.06664
- Mozannar, H. & Sontag, D. (2020). Consistent Estimators for Learning to Defer to an Expert. arXiv:2006.01862
- Ong, I. et al. (2024). RouteLLM: Learning to Route LLMs with Preference Data. arXiv:2406.18665
- Chen, L., Zaharia, M. & Zou, J. (2023). FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance. arXiv:2305.05176
- Teerapittayanon, S., McDanel, B. & Kung, H. T. (2016). BranchyNet: Fast Inference via Early Exiting from Deep Neural Networks. arXiv:1709.01686
- Leviathan, Y., Kalman, M. & Matias, Y. (2023). Fast Inference from Transformers via Speculative Decoding. arXiv:2211.17192
- Chen, C. et al. (2023). Accelerating Large Language Model Decoding with Speculative Sampling. arXiv:2302.01318
C.8교과서와 개관
- Goodfellow, I., Bengio, Y. & Courville, A. (2016). Deep Learning.
- Hastie, T., Tibshirani, R. & Friedman, J. (2009). The Elements of Statistical Learning (2nd ed.).
- Bishop, C. M. & Bishop, H. (2024). Deep Learning: Foundations and Concepts.
- Murphy, K. P. (2022). Probabilistic Machine Learning: An Introduction.
- Murphy, K. P. (2023). Probabilistic Machine Learning: Advanced Topics.
- Prince, S. J. D. (2023). Understanding Deep Learning.
- Zhang, A., Lipton, Z. C., Li, M. & Smola, A. J. (2023). Dive into Deep Learning.
Appendix D용어 색인
본문에서 처음 정의되거나 강조된 용어(굵게 표시된 용어)를 알파벳 순으로 모았다. 오른쪽 번호는 그 용어가 나오는 절이며, 여러 곳에 나오면 앞의 네 곳까지 보인다.
A
- activation function 2.3
- ActNorm 19.3
- AdaIN 16.7
- AdamW 4.4
- Adaptive instance normalization 16.7
- advantage 25.1
- Affine coupling layer 19.3
- Aleatoric uncertainty 21.1
- alignment 12.5
- Alignment and uniformity 12.5
- all-reduce 28.1
- Alternative hypothesis 1.6
- Amortized inference 15.5
- Asymptotic normality 1.4
- Asymptotic properties of MLE 1.4
- attention 7.6
- attribution map 13.1
- AUC 22.5
- Autoencoder 15.2
- automatic differentiation 4.2
- autoregressive 8.6
- average pooling 6.5
B
- Backpropagation 4.2
- Backpropagation for MLP 4.2
- backpropagation through time 7.4
- Barlow Twins 12.5
- baseline hazard 24.4
- Batch normalization 4.6
- Bayes classifier for the balanced error 14.3
- Bayes-optimal router and the oracle gap 30.3
- Bayes-optimal threshold 22.5
- Bellman optimality operator is a contraction 25.6
- benign overfitting 5.3
- bias 2.3
- Bias, MSE, Consistency 1.3
- Bias–variance decomposition 1.3
- Bidirectional RNN 7.5
- binary cross-entropy 1.8, 3.2
- bits per dimension 19.5
- bootstrap 22.7
- bottleneck 6.6
- Bradley–Terry model 26.4
- BYOL 12.5
- Byte array 9.6
- Byte-pair encoding 26.1
C
- calibrated 21.4
- Calibration 21.4
- CAM 13.4
- CBOW 7.2
- cell state 7.5
- chain rule of entropy 3.5
- Change of variables 19.1
- cheap gradient principle 4.2
- class activation map 13.4
- class-discriminative 13.3
- classifier 2.7
- CLIP 12.9
- closed form 1.8
- Closed-form marginal 18.2
- competing risks 24.8
- Composition of affine maps 2.2
- computational graph 4.2
- Concavity of the log partial likelihood 24.5
- concordance index 24.6
- Conditional flow matching 20.4
- Conditional GAN 16.6
- Conformal prediction 21.7
- Consistency 1.4
- consistent 1.3
- continuity equation 19.6
- control variate 25.3
- Convergence to stationarity 4.1
- cosine annealing 4.4
- cosine similarity 7.1
- Coverage of split conformal prediction 21.7
- Cox partial likelihood 24.5
- Cox proportional hazards model 24.4
- cross-correlation 6.3
- Cross-entropy, KL divergence 3.3
- Cumulative hazard 24.1
- CutMix 12.10
- cyclic LR 4.4
D
- DANN 23.4
- Data augmentation 4.7
- data leakage 22.2
- Data parallelism equals large-batch SGD 28.1
- DDIM sampling step 18.6
- DeepSurv 24.7
- degradation problem 6.6
- Denoising score matching 17.3
- Depthwise separable convolution 6.5
- dequantization 19.5
- Descent lemma 4.1
- Deterministic model 1.1
- differential entropy 3.3
- Diffusion ELBO decomposition 18.3
- DINO 12.5
- DINOv2 12.5
- Dirichlet energy 11.4
- Discriminative model 15.1
- distributional hypothesis 7.2
- double descent 5.3
- dummy encoding 1.8
E
- early stopping 4.7, 5.4
- edge of stability 5.5
- effective sample size 23.2
- embedding 2.7, 7.1
- Embedding matrix 7.1
- empirical risk 5.1
- empirical risk minimization 5.1
- Encoder 2.7
- end-to-end learning 2.1
- energy-based model 17.1
- Entropy bounds 3.3
- Epistemic uncertainty 21.1
- epoch 4.3
- equivariance 6.4
- error signal 4.2
- estimate 1.3
- estimation 1.3
- estimator 1.3
- evidence 1.5
- Evidence lower bound (ELBO) 15.4
- Exact risk of min-norm least squares 5.3
- expected calibration error 21.4
- exponential decay 4.4
F
- feature 2.7
- feature map 2.7
- feed-forward network 8.5
- Finite hypothesis class 5.2
- Fisher divergence 17.2
- Fisher information 1.4
- FixMatch 14.1
- Fokker–Planck equation 20.2
- $K$-fold cross-validation 22.3
- Forward (diffusion) process 18.2
- Forward loss correction 14.2
- Forward posterior 18.2
- forward process 2.6
- Foundation model 12.8
- Fréchet Inception Distance 18.9
- full-batch 4.3
- fully-connected network 2.3
G
- GAN 16.2
- GAN minimizes JSD 16.3
- Gaussian KL 15.7
- generalization gap 5.1
- Generalized advantage estimation 25.3
- Generative model 15.1
- Gibbs' inequality 3.3
- Global average pooling 6.5
- Grad-CAM 13.5
- Grad-CAM generalizes CAM 13.5
- gradient check 4.2
- gradient clipping 7.4
- gradient descent 4.1
- Gradient descent finds the min-norm interpolator 5.4
- gradient noise scale 28.5
- Gradient of softmax cross-entropy 3.6
- Gradient of the MoE log-likelihood 30.1
- Gram matrix 16.7
- Graph attention network 11.5
- graph Fourier transform 11.4
- graph isomorphism network 11.6
- graph Laplacian 11.4
- GraphSAGE 11.5
- Group-relative baselines 25.5
- grouped-query attention 10.1
- GRU 7.5
H
I
- I-JEPA 12.6
- im2col 6.3
- implicit generative model 16.1
- implicit regularization 5.4
- Importance-weighted risk 23.2
- In-context learning 26.2
- Inception Score 18.9
- inductive bias 6.4
- inference 1.3
- InfoNCE bound 12.4
- information 3.3
- Instantaneous change of variables 19.6
- integrated gradients 13.2
- interpolation threshold 5.3
- intrinsic dimension 29.2
- invariance 1.4, 6.4
- Invariance and equivariance on graphs 11.2
- Inverse and log-determinant of affine coupling 19.3
- inverted dropout 4.7
- Invertible 1×1 convolution 19.3
- iteration 4.3
J
- Jensen–Shannon divergence 16.3
L
- Langevin dynamics 17.4
- Laplacian quadratic form 11.4
- latent array 9.6
- latent vector 2.7
- lazy training 5.6
- learning rate 4.1
- least squares estimator 1.8
- Likelihood 1.4
- likelihood function 1.4
- linear probe 12.1
- linear scaling rule 4.3, 5.5
- Locality 6.4
- Log score and Brier score are strictly proper 21.5
- logistic regression 1.8
- logit 2.3
- LoRA 12.7
- loss function 16.2
- LSTM 7.5
M
- MAE 12.6
- Mamba 10.6
- manifold hypothesis 12.1
- Marginal of the VP SDE 20.1
- Marginal vector field 20.4
- Markov decision process 25.1
- Max pooling 6.5
- maximum a posteriori 1.5
- Maximum likelihood estimator 1.4
- MC dropout 21.3
- Message passing is permutation equivariant 11.3
- Message passing neural network 11.3
- Min-norm least squares 5.3
- mini-batch 4.3
- minimum-norm least squares 5.3
- Mixup 12.10
- MoCo 12.4
- Multi-head attention 8.4
- multi-label 3.2
- multi-layer perceptron 2.3
- mutual information 3.5
N
O
- objective function 16.2
- OLS = Gaussian MLE 1.8
- one-cycle 4.4
- one-hot 7.1
- one-hot encoding 1.8
- Online softmax 10.3
- Optimal compensation 29.5
- Optimal discriminator 16.3
- Optimal policy of KL-regularized reward maximization 26.6
- Output size, parameter count, cost 6.3
- over-smoothing 11.7
- Over-smoothing of linear propagation 11.7
- over-squashing 11.7
- overfitting 4.7
P
- p-value 1.6
- PAC-Bayes bound 5.5
- padding mask 8.6
- parallel scan 10.6
- parameter 1.2
- parametric family 1.2
- Perceiver 9.6
- Performance difference 25.4
- Permutation equivariance 8.2
- permutation equivariant 11.2
- permutation invariant 11.2
- perplexity 26.1
- Policy 25.1
- Policy gradient theorem 25.2
- Pooling 6.5
- population 1.3
- posterior 1.5
- Posterior correction under label shift 23.3
- PPO 25.4, 26.5
- pre-activation 2.3
- Precision depends on prevalence 22.4
- precision–recall curve 22.5
- prediction 1.3
- pretext task 12.2
- Probabilistic meaning of AUC 22.5
- probability density function 1.2
- Probability flow ODE 20.3
- probability integral transform 19.1
- probability mass function 1.2
- proper 21.5
- Properties of group baselines 25.5
- Properties of temperature scaling 21.6
- proportional hazards 24.4
- Pseudo-labeling 14.1
R
- Rademacher complexity 5.2
- RandAugment 12.10
- Random variable 1.2
- readout 11.3
- receptive field 6.4
- reconstruction 15.4
- rectified flow 20.4
- Recurrence–convolution duality 10.5
- regularization 4.7, 15.4
- Relations among f, S, h, H 24.1
- Relative position as rotation 8.3
- reliability diagram 21.4
- renormalization trick 11.4
- representation 2.7
- representation collapse 12.5
- representation space 12.1
- Residual block 6.6
- Reverse process 18.3
- Reverse-time SDE 20.2
- reward hacking 26.5
- right censoring 24.2
- risk 5.1
- risk set 24.3
- RLHF 26.3
- ROC curve 22.5
- RoPE depends only on relative position 10.2
- Rounding error of uniform quantization 29.3
- Routing 30
S
- S4 10.5
- sample 1.3
- sample space 1.2
- Sample space, Random variable 1.2
- sampling distribution 1.3
- saturation 2.4
- scalability 9.3
- Scaled dot-product attention 8.1
- score equation 1.4
- score function 17.1
- Score matching 17.2
- selective prediction 21.8
- self-attention 8.2
- self-information 3.3
- Self-information, Entropy 3.3
- semi-parametric 24.4
- Shannon entropy 3.3
- sharpness 5.5
- sharpness-aware minimization 5.5
- shifted right 8.6
- SimCLR 12.4
- SimSiam 12.5
- sinusoidal positional encoding 8.3
- Skip-gram 7.2
- softmax 2.3
- speculative decoding 30.4
- Speculative sampling is exact 30.4
- Step decay 4.4
- stochastic (probabilistic) model 1.1
- stochastic gradient descent 4.3
- Straight-through estimator 29.6
- strictly proper 21.5
- student 12.11
- surrogate 3.1
- surrogate objective 25.4
- Survival function 24.1
- survival time 24.1
- Survival, hazard, cumulative hazard 24.1
- Symmetric losses are noise-tolerant 14.2
T
U
V
W
X
- Xavier (Glorot) 4.5
Z
- zero-shot classification 12.9