5 분 소요

이 포스팅은 Variational Inference(VI) 를 정리한 글입니다.


Introduction

베이지안 추론의 목표는 관측 데이터 $y$ 에 대해 사후분포(posterior)

\[p(\theta \mid y) \propto p(\theta)\, p(y \mid \theta)\]

를 계산하는 것입니다.

하지만 실제로는

  • 복잡한 likelihood
  • 고차원 파라미터
  • 비선형/비가우시안 모델

때문에 정규화 상수인 evidence

\[p(y) = \int p(\theta)\,p(y\mid\theta)\,d\theta\]

를 닫힌형태로 구할 수 없는 경우가 대부분입니다.

전통적으로는

  • MCMC, SMC, Particle Filter 등 샘플링 기반 방법
  • Laplace approximation, EP 등 근사 방법

이 사용되어 왔고, 그 중에서 Variational Inference(VI)

“샘플링 문제를 최적화 문제(Optimization)로 바꿔서 푸는 근사 베이지안 추론 방법”

으로 이해할 수 있습니다.


Variational Inference의 핵심 아이디어

아이디어는 아주 간단합니다.

  1. 복잡한 posterior $p(\theta\mid y)$ 대신
  2. “계산 가능한” 분포족 $\mathcal{Q}$ 안에서 하나의 분포 $q(\theta)$를 골라
  3. $p(\theta\mid y)$ 와 최대한 비슷하게 만들자.

즉,

posterior를 직접 샘플링하지 않고,
잘 다룰 수 있는 분포 $q(\theta)$”로 근사하자.

이를 위해 KL divergence 를 사용합니다.


KL 최소화 관점

우리가 하고 싶은 것은

\[q^\star(\theta) = \arg\min_{q \in \mathcal{Q}} \text{KL}\big(q(\theta) \,\|\, p(\theta\mid y)\big)\]

입니다.

여기서 KL divergence는

\[\text{KL}\big(q \,\|\, p\big) = \mathbb{E}_q \big[ \log q(\theta) - \log p(\theta) \big]\]

로 정의됩니다.

Posterior에 대해서 쓰면

\[\text{KL}\big(q(\theta)\,\|\, p(\theta\mid y)\big) = \mathbb{E}_q \big[ \log q(\theta) - \log p(\theta\mid y) \big].\]

Bayes 공식 $p(\theta\mid y) = p(y,\theta)/p(y)$ 를 대입하면 \(\begin{align} \text{KL}\big(q \,\|\, p(\theta\mid y)\big) &= \mathbb{E}_q \big[ \log q(\theta) - \log p(y,\theta) + \log p(y) \big] \\ &= \underbrace{ \mathbb{E}_q[\log q(\theta)] - \mathbb{E}_q[\log p(y,\theta)] }_{\text{(1)}} + \log p(y). \end{align}\) 여기서 $\log p(y)$ 는 $\theta$와 무관한 상수입니다.

따라서

  • KL을 최소화하는 대신
  • 아래 항을 최대화해도 동일한 해를 얻습니다.
\[\mathcal{L}(q) = \mathbb{E}_q[\log p(y,\theta)] - \mathbb{E}_q[\log q(\theta)].\]

이 $\mathcal{L}(q)$ 를 Evidence Lower Bound (ELBO) 라고 부릅니다.


ELBO: Evidence Lower Bound

위 식을 정리하면,

\[\log p(y) = \mathcal{L}(q) + \text{KL}\big(q(\theta)\,\|\,p(\theta\mid y)\big).\]
  • $\log p(y)$ : 고정된 상수 (모델 evidence)
  • KL ≥ 0 이므로
\[\mathcal{L}(q) \le \log p(y).\]

따라서 ELBO는 이름 그대로 evidence에 대한 하한(lower bound) 입니다.

또한, KL 최소화와 ELBO 최대화가 동치이므로

\[q^\star(\theta) = \arg\max_{q\in\mathcal{Q}} \mathcal{L}(q).\]

즉,

VI는 “ELBO 최대화 문제”를 푸는 것과 완전히 같게 됩니다.


Interpretaion of ELBO

ELBO는 두 항으로 분해됩니다. \(\begin{align} \mathcal{L}(q) &= \mathbb{E}_q[\log p(y,\theta)] - \mathbb{E}_q[\log q(\theta)] \\ &= \mathbb{E}_q[\log p(y\mid \theta)] + \mathbb{E}_q[\log p(\theta)] - \mathbb{E}_q[\log q(\theta)]. \end{align}\) 이를 해석하면

  • $\mathbb{E}_q[\log p(y\mid\theta)]$ : expected log-likelihood
    → 데이터 적합도(fit)
  • $-\text{KL}(q(\theta)\,|\,p(\theta))$
    → prior와 q 사이의 거리 (regularization 역할)

즉 ELBO는

“데이터 적합도 + prior regularization − 엔트로피 패널티”

로 해석할 수 있습니다.


Variational Family

VI의 성능은 어떤 family $\mathcal{Q}$를 선택하느냐에 강하게 의존합니다.

대표적인 선택은 다음과 같습니다.

  1. Mean-field family

    \[q(\theta) = \prod_{j=1}^d q_j(\theta_j)\]
    • 각 파라미터/블록이 서로 독립이라고 가정
    • 계산이 매우 단순해짐 (coordinate ascent 가능)
    • 하지만 의존구조(correlation)를 표현하지 못함
  2. Full-covariance Gaussian

    \[q(\theta) = \mathcal{N}(\mu, \Sigma)\]
    • 공분산까지 학습하여 상관관계 표현 가능
    • 파라미터 수가 $O(d^2)$ 로 증가
  3. Mixture / Normalizing flow 등 리치한 family

    • Mixture of Gaussians
    • Normalizing Flows 기반 $q(\theta)$
    • 매우 표현력이 높지만 최적화가 더 어려움

이 글에서는 가장 기본이 되는 mean-field VI 를 중심으로 설명하겠습니다.


Mean-field VI와 Coordinate Ascent

Mean-field 가정:

\[q(\theta) = \prod_{j=1}^M q_j(\theta_j).\]

이때, ELBO는

\[\mathcal{L}(q_1,\dots,q_M) = \mathbb{E}_{q}[\log p(y,\theta)] - \sum_{j=1}^M \mathbb{E}_{q_j}[\log q_j(\theta_j)].\]

여기서 중요한 것은:

나머지를 고정하고 하나의 factor $q_j$만 최적화 하면,
닫힌형태의 update 식을 얻을 수 있다.

정확히는,

\[\log q_j^\star(\theta_j) = \mathbb{E}_{q_{-j}}[\log p(y,\theta)] + \text{const},\]

여기서 $q_{-j}$ 는 $j$번째를 제외한 모든 factor의 곱입니다.

즉,

“joint log density를 기대값 취해서 exponentiation → 정규화”
를 반복하면 된다.

알고리즘 (CAVI: Coordinate Ascent VI)

  1. 초기화: $q_j^{(0)}(\theta_j)$ 적당히 설정
  2. 반복 (j = 1,…,M 순회)

    \[\log q_j^{\text{new}}(\theta_j) \propto \mathbb{E}_{q_{-j}^{\text{old}}}[\log p(y,\theta)].\]
  3. 모든 $j$ 에 대해 업데이트 후, ELBO 수렴 시까지 반복

이 방식은 conjugate exponential family 구조에서 closed-form update를 제공하여,

  • LDA
  • Bayesian mixture model
  • Factor analysis

등 여러 모델에 대해 “논문 한 편 = CAVI 업데이트 유도” 가 되는 경우가 많습니다.


Exponential Family와 Conjugacy

만약 joint 분포 $p(y,\theta)$ 가 exponential family 구조를 가지고 있고, prior–likelihood가 conjugate 하다면,

각 factor $q_j(\theta_j)$ 역시 동일한 family에 속하게 됩니다.

예를 들어,

  • Likelihood: $p(y\mid\theta)$ 는 Gaussian
  • Prior: $p(\theta)$ 도 Gaussian
  • Posterior: $p(\theta\mid y)$ 도 Gaussian (conjugate)

이때 Mean-field VI를 적용하면,

  • $q(\theta)$도 Gaussian
  • update는 “posterior의 natural parameter에 expectation만 집어넣은 형태”로 표현

→ 완전히 analytic update가 가능해집니다.


Stochastic Variational Inference (SVI)

문제는:

  • 데이터 $y = (y_1,\dots,y_N)$ 가 매우 클 때
  • 매 step마다 $\mathbb{E}_q[\log p(y,\theta)]$ 를 계산하는 것은 비현실적

mini-batch 기반 stochastic gradient 를 사용하자.

SVI는

  1. ELBO를 stochastic gradient ascent 로 최적화
  2. 각 step에서 mini-batch 데이터만 사용
  3. learning rate $\rho_t$ 를 줄여가며 수렴 보장

Score Function Gradient (REINFORCE)

ELBO를 $\mathcal{L}(\lambda)$, $q(\theta;\lambda)$ 라 쓰면 $$ \begin{align} \mathcal{L}(\lambda) &= \mathbb{E}{q(\theta;\lambda)}[\log p(y,\theta)] - \mathbb{E}{q(\theta;\lambda)}[\log q(\theta;\lambda)]. \end{align}

score function trick을 쓰면,

\begin{align} \nabla_\lambda \mathcal{L}(\lambda) &= \mathbb{E}{q(\theta;\lambda)} \big[ \nabla\lambda \log q(\theta;\lambda) \big( \log p(y,\theta) - \log q(\theta;\lambda) \big) \big]. \end{align} $$ 이를 Monte Carlo로 근사하면,

  1. $\theta^{(s)} \sim q(\theta;\lambda)$
\[\hat{g} = \frac{1}{S} \sum_{s=1}^S \nabla_\lambda \log q(\theta^{(s)};\lambda) \big( \log p(y,\theta^{(s)}) - \log q(\theta^{(s)};\lambda) \big).\]
  1. $\lambda \leftarrow \lambda + \rho_t \hat{g}$

하지만 이 gradient는 분산이 매우 크다는 단점이 있습니다.


Reparameterization Trick

최근 딥러닝에서 쓰는 VI(예: VAE)는 대부분 reparameterization gradient 를 사용합니다.

아이디어:

  • $q(\theta;\lambda)$에서 직접 샘플하지 말고
  • 고정 분포 $\epsilon \sim p(\epsilon)$ 에서 샘플한 뒤
  • $\theta = g(\epsilon;\lambda)$ 로 변환해서 얻기

예: Gaussian $q(\theta;\mu,\sigma^2)$

  • $\epsilon \sim \mathcal{N}(0,1)$
  • $\theta = \mu + \sigma \epsilon$

그러면

\[\mathcal{L}(\lambda) = \mathbb{E}_{\epsilon\sim p(\epsilon)} \big[ \log p(y, g(\epsilon;\lambda)) - \log q(g(\epsilon;\lambda);\lambda) \big].\]

이제 gradient는 \(\begin{align} \nabla_\lambda \mathcal{L}(\lambda) &= \mathbb{E}_{\epsilon} \big[ \nabla_\lambda \big( \log p\big(y, g(\epsilon;\lambda)\big) - \log q\big(g(\epsilon;\lambda);\lambda\big) \big) \big]. \end{align}\)

  • $\epsilon$ 은 $\lambda$ 와 무관
  • 안쪽의 gradient는 일반적인 backprop으로 계산 가능
  • 분산이 작은 gradient estimator 확보

그래서 VAE, Bayesian neural net 등에서는

  • encoder $q_\phi(z\mid x)$
  • decoder $p_\theta(x\mid z)$

를 두고, reparameterization trick + SGD로 ELBO를 최적화합니다.


VI vs MCMC / SMC

간단히 요약하면:

방법 핵심 아이디어 장점 단점
MCMC Markov chain으로 posterior 샘플링 이론적으로 정확 (시간→∞) 느릴 수 있음, mixing 문제
SMC / PF Sequential하게 importance sampling + resampling online, non-linear/non-Gaussian state space에 강함 high-dim에서 particle 수 폭발
VI 최적화를 통해 근사 posterior 학습 빠름, 대규모 데이터에 좋음 mode-seeking, uncertainty 과소추정 가능

특히 VI는

  • KL$(q|p)$ 를 최소화하기 때문에
  • posterior의 tail / 작은 모드 를 무시하고
  • 주요 모드 근처에 mass를 집중시키는 경향(mode-seeking)이 있습니다.

이 부분은 나중에 Predictive VI / Proper Scoring Rule 기반 VI 등으로 보완할 수 있습니다.


예시: Bayesian Logistic Regression에서의 VI

간단한 예로, Bayesian logistic regression을 생각해봅시다.

  • 데이터: $(x_i,y_i)$, $y_i\in{0,1}$
  • 파라미터: $\beta\in\mathbb{R}^p$

모델: \(\begin{align} y_i \mid x_i,\beta &\sim \text{Bernoulli}(\sigma(x_i^\top\beta)), \\ \beta &\sim \mathcal{N}(0,\alpha^{-1}I). \end{align}\)

  • posterior $p(\beta\mid y)$ 는 closed form 없음
  • MCMC도 가능하지만, 큰 데이터에서는 느릴 수 있음

여기서 VI:

  • $q(\beta)$ 를 Gaussian $\mathcal{N}(m,S)$ 로 가정
  • ELBO:

    \[\mathcal{L}(m,S) = \mathbb{E}_q[\log p(y\mid\beta)] + \mathbb{E}_q[\log p(\beta)] - \mathbb{E}_q[\log q(\beta)].\]
  • $\mathbb{E}_q[\log p(y\mid\beta)]$ 는 analytic하지 않지만
    → Monte Carlo + reparameterization 로 gradient 구해서
    → $(m,S)$ 에 대해 SGD 수행

이 구조가 Bayesian deep learning, VAE 등으로 그대로 확장됩니다.


VI는 언제 좋고, 언제 나빠질까

좋은 경우

  • posterior가 거의 unimodal
  • mean-field 근사로도 크게 정보 손실이 없는 경우
  • 아주 큰 데이터셋, deep model처럼 MCMC가 비현실적인 경우

나빠지는 경우

  • posterior가 강하게 multi-modal
  • 변수 간 강한 상관관계가 있음에도 factorized family 사용
  • model misspecification 하에서 uncertainty를 과소추정하는 경우

Summary:

  • VI는 posterior 추론을 최적화 문제(ELBO 최대화) 로 바꾸는 방법이다.
  • Mean-field VI는 계산이 간단하지만 상관구조를 잃기 쉽다.
  • Stochastic VI + reparameterization은 딥러닝에서는 사실상 표준이다.
  • KL$(q|p)$ 특성 때문에 mode-seeking + 과도한 확신이라는 한계가 있다.

Reference

업데이트:

댓글남기기