from torch.nn.functional import relu, softplus16.2 적대적 목적 함수와 발산
대부분의 GAN 구현체는 비포화 로지스틱 손실, 최소제곱 손실(LSGAN), 힌지 손실, Wasserstein 손실처럼 서로 바꿔 끼울 수 있는 여러 훈련 목적 함수를 제공합니다. 16.1절 에서는 로지스틱 목적 함수를 분석하여 최적 판별자가 로그 밀도비 \(\lambda(x) = \log(p(x)/q(x))\) 를 복원하고 미니맥스 가치가 \(p\) 와 \(q\) 의 지지집합이 더 이상 겹치지 않으면 포화되는 수량인 젠센–섀넌 발산임을 보였습니다. 그렇다면 다른 목적 함수들은 어떤 발산을 측정할까요? 또한 생성 샘플이 데이터에서 멀리 떨어져 있을 때 그레이디언트 소실은 손실 함수, 크리틱 아키텍처, 기저 발산 중 어디서 비롯될까요?
이 부류의 모든 목적 함수는 크리틱 출력에 적용하는 채점 함수를 바꾸거나 크리틱이 최적화하는 함수족 \(\mathcal{T}\) 를 바꿉니다. 비제약 크리틱을 분류 손실과 짝지으면 점별 밀도비 \(p(x)/q(x)\) 에만 의존하는 \(f\)-발산을 평가합니다. 그 대신 선형 보수를 쓰면서 크리틱을 매끄러운 함수족으로 제약하면 지지집합이 서로소일 때도 공간 거리에 민감하게 반응하는 최대 평균 불일치(MMD)나 Wasserstein-1 거리(\(W_1\)) 같은 적분 확률 거리(integral probability metric, IPM)를 얻습니다. 아래에서 두 부류를 모두 유도하고 분리된 1차원 가우스 분포들과 2차원 가우스 혼합 분포 위에서 거동을 비교합니다.
# Deterministic GPU kernels; JAX reads XLA_FLAGS once, before the imports
import os
os.environ['XLA_FLAGS'] = (os.environ.get('XLA_FLAGS', '') +
' --xla_gpu_deterministic_ops=true').strip()from jax.nn import relu, softplus16.2.1 일반 템플릿
16.1절 에서 크리틱은 실제 샘플 \(x \sim p\) 에 대해 \(\log \sigma(D(x))\) 를, 생성 샘플 \(x' \sim q\) 에 대해 \(\log \sigma(-D(x'))\) 를 받았습니다. 이 로그 가능도 항들을 크리틱 함수족 \(\mathcal{T}\) 위의 일반 보수 함수 \(\ell_p\) 와 \(\ell_q\) 로 바꾸면 일반 적대적 불일치 척도를 얻습니다:
\[ \begin{aligned} d(p, q) &= \sup_{T \in \mathcal{T}} \Big\{ \mathbb{E}_{x \sim p}\big[\ell_p(T(x))\big] \\ &\qquad\qquad + \mathbb{E}_{x' \sim q}\big[\ell_q(T(x'))\big] \Big\}. \end{aligned} \tag{16.2.1}\]
\(\mathcal{T}\) 에 제약을 두지 않은 채 \(\ell_p(t) = \log \sigma(t)\), \(\ell_q(t) = \log \sigma(-t)\) 로 두면 \(2\,\mathrm{JS}(p, q) - 2\log 2\) 가 복원됩니다. 이 절 전반에서 크리틱은 기대 보수 합을 최대화합니다(동치로, 크리틱 손실이라 부르는 음의 보수를 최소화합니다).
표 16.2.1 에서는 크리틱이 개별 샘플을 채점하는지 실제–생성 쌍을 채점하는지, 그리고 크리틱 함수족 \(\mathcal{T}\) 가 비제약인지 정칙화되는지의 두 축을 따라 이 장의 목적 함수들을 분류합니다.
임의의 고정된 크리틱 \(T\) 에 대해 식 16.2.1 내부의 기댓값은 분포 \(q\) 에 대해 선형이라는 점에 주목합시다. 선형 범함수족의 상한(supremum)은 볼록 함수이므로 고정된 \(p\) 에 대해 \(d(p, q)\) 는 확률 측도 \(q\) 에 대해 항상 볼록합니다. 그러나 신경망 \(G_\theta\) 로 매개변수화된 분포들의 집합 \(\{q_\theta\}\) 는 볼록 집합이 아니므로 분포 공간에서의 볼록성이 생성자 매개변수 \(\theta\) 에 대한 볼록성을 함의하지는 않습니다(1 참조).
16.2.2 분류 손실과 \(f\)-발산
16.2.2.1 두 결과 예제
동일한 사전 확률 \(\tfrac12\) 로 샘플링되는 데이터 분포 \(p = (\tfrac34, \tfrac14)\) 와 생성자 분포 \(q = (\tfrac14, \tfrac34)\) 를 가진 이진 결과 공간(앞면과 뒷면)을 생각해 봅시다. 결과를 관측했을 때 그것이 \(p\) 에서 나왔을 베이즈 사후 확률은 \(\eta = p/(p + q)\) 로 앞면에서는 \(\tfrac34\), 뒷면에서는 \(\tfrac14\) 입니다. 결과를 보지 않는 맹목적 예측(\(D = 0\))은 결과와 무관하게 \(\tfrac12\) 을 예측합니다. 결과를 관측함으로써 얻는 기대 손실 감소량은 분류 손실에 따라 달라집니다:
- 로그 손실: 최적 예측 \(\eta\) 는 맹목적 추측의 \(\log 2 = 0.693\) nat 대비 이진 엔트로피 \(H_b(\tfrac34) = 0.562\) nat을 달성하여 \(0.131\text{ nats} = \mathrm{JS}(p, q)\) 만큼 절감합니다.
- 확률 위의 제곱 오차: \(\eta\) 를 예측하면 \(\tfrac12\) 예측의 \(\tfrac14\) 대비 기대 손실 \(\tfrac34 \cdot \tfrac14 = \tfrac{3}{16}\) 을 달성하여 \(\tfrac{1}{16}\) 을 절감합니다.
- 점수 \(t\) 위의 힌지 손실: 최적 점수 \(t = +1\)(앞면)과 \(t = -1\)(뒷면)은 \(t = 0\) 에서의 \(1\) 대비 기대 손실 \(2 \cdot \tfrac14 = \tfrac12\) 을 달성하여 \(\tfrac12 = \mathrm{TV}(p, q) = \tfrac12 \sum |p - q|\) 를 절감합니다.
각 손실은 동일한 사후 확률 \(\eta\) 에 기반해 같은 쌍 \((p, q)\) 에 서로 다른 음이 아닌 발산을 부여합니다. 이제 모든 마진 기반 분류 손실이 \(f\)-발산을 정의함을 보입시다.
16.2.2.2 베이즈 위험 격차
대칭 분류 손실은 실제 샘플의 \(D(x)\) 와 생성 샘플의 \(-D(x')\) 에 동일한 단일 마진 보수 \(\ell\) 을 적용합니다(\(\ell_p(t) = \ell(t)\), \(\ell_q(t) = \ell(-t)\)):
\[ V_\ell(D) \;=\; \mathbb{E}_{x \sim p}\big[\ell(D(x))\big] + \mathbb{E}_{x' \sim q}\big[\ell(-D(x'))\big]. \tag{16.2.2}\]
여기서 부호 있는 점수 \(t\)(실제 데이터에서는 \(+D(x)\), 생성 데이터에서는 \(-D(x')\))가 분류 마진(margin)입니다. 각 점 \(x\) 에서 \(m = (p+q)/2\), \(\eta(x) = p(x)/(p(x)+q(x))\) 에 대해 \(p(x)\ell(t) + q(x)\ell(-t) = 2m(x)\big[\eta(x)\ell(t) + (1 - \eta(x))\ell(-t)\big]\) 가 성립합니다. 사후 확률 \(\eta\) 에서의 점별 최소 기대 손실이 조건부 베이즈 위험(conditional Bayes risk)입니다:
\[ L(\eta) \;=\; \inf_{t} \Big\{ \eta \, \big({-\ell(t)}\big) + (1 - \eta)\, \big({-\ell(-t)}\big) \Big\}. \tag{16.2.3}\]
\(\eta\) 에 대한 아핀 함수들의 하한(infimum)이므로 \(L(\eta)\) 는 \([0, 1]\) 위에서 오목 함수입니다. 상수 크리틱(\(t = 0\))은 위험 \(L(\tfrac12)\) 을 달성합니다. \(x\) 를 관측함으로써 줄어드는 위험 감소량이 베이즈 위험 격차(Bayes-risk gap)입니다:
\[ \Delta_\ell(p, q) \;=\; L(\tfrac12) - \mathbb{E}_{x \sim m}\big[L(\eta(x))\big], \tag{16.2.4}\]
이 격차가 최적 가치 \(\sup_D V_\ell(D) = 2\Delta_\ell(p, q) - 2L(\tfrac12)\) 를 결정합니다. 옌센 부등식과 \(\mathbb{E}_m[\eta] = \tfrac12\) 에 의해 \(\Delta_\ell(p, q) \geq 0\) 이 성립합니다.
16.2.2.3 \(f\)-발산으로서의 베이즈 위험 격차
25.3.1.2절 에서 배웠듯 \(f\)-발산은 \(q\) 아래에서 밀도비 \(\rho(x) = p(x)/q(x)\) 의 볼록 함수 \(f\)(\(f(1) = 0\)) 평균을 냅니다: \(D_f(p \,\|\, q) = \mathbb{E}_{x \sim q}[f(\rho(x))]\).
명제. 조건부 베이즈 위험 \(L\) 이 \([0, 1]\) 위에서 유한하면 다음이 성립한다:
\[ \begin{aligned} \Delta_\ell(p, q) &= D_f(p \,\|\, q) \\ \textrm{with}\quad f(u) &= L(\tfrac12) - \frac{u+1}{2}\, L\!\left(\frac{u}{u+1}\right), \end{aligned} \]
여기서 \(f\) 는 \([0, \infty)\) 위의 볼록 함수이고 \(f(1) = 0\) 이다.
증명. \(u = \rho = p/q\) 를 대입하면 \(m = q\,(u+1)/2\) 및 \(\eta = u/(u+1)\) 이므로
\[ \mathbb{E}_{x \sim m}\big[L(\eta(x))\big] = \int q \, \frac{u+1}{2}\, L\!\left(\frac{u}{u+1}\right), \]
을 얻고 \(L(\tfrac12) = \int q\, L(\tfrac12)\) 을 적분 안으로 옮기면 \(\Delta_\ell(p, q) = \mathbb{E}_q[f(\rho)]\) 가 나온다. 오목 함수 \(L(v) = \inf_j \{\alpha_j v + \beta_j\}\) 를 접선들의 하포락선으로 쓰면 \((u+1)L(u/(u+1)) = \inf_j \{\alpha_j u + \beta_j(u+1)\}\) 이 \(u\) 에 대해 오목 함수임을 알 수 있으므로 \(f(u)\) 는 볼록 함수이고 \(f(1) = L(\tfrac12) - L(\tfrac12) = 0\) 이다. \(\blacksquare\)
따라서 비제약 크리틱과 결합한 모든 대칭 분류 손실은 \(f\)-발산을 평가하며, 최적 크리틱 \(D^\star(x)\) 는 로그 밀도비 \(\lambda(x) = \log(p(x)/q(x))\) 의 단조 연결 함수(link function)가 됩니다.
16.2.2.4 주요 분류 손실들의 발산
표 16.2.2 에 네 가지 표준 분류 손실과 각각의 조건부 베이즈 위험 \(L(\eta)\), 베이즈 위험 격차 \(\Delta_\ell(p, q)\), 최적 크리틱 연결 함수 \(D^\star(\lambda)\), 그리고 함께 쓰이는 실전 생성자 손실을 정리했습니다.
| 손실 | 마진 손실 \(-\ell(t)\) | 베이즈 위험 \(L(\eta)\) | 격차 \(\Delta_\ell(p,q)\) | 최적 크리틱 연결 함수 | 생성자 손실 |
|---|---|---|---|---|---|
| 로지스틱 | \(\log(1 + e^{-t})\) | \(H_b(\eta)\) | \(\mathrm{JS}(p,q)\) | \(\lambda\) | \(-\log \sigma(D)\) |
| 최소제곱(LSGAN) | \(\tfrac14 (1 - t)^2\), \(t = 2D - 1\) | \(\eta(1-\eta)\) | \(\tfrac{1}{8}\int \frac{(p-q)^2}{p+q}\) | \(\sigma(\lambda)\) | \(\tfrac12 (D - 1)^2\) |
| 제곱 힌지 | \(\max(0, 1 - t)^2\) | \(4\eta(1-\eta)\) | \(\tfrac{1}{2}\int \frac{(p-q)^2}{p+q}\) | \(\tanh(\lambda/2)\) | \(-D\) |
| 힌지 | \(\max(0, 1 - t)\) | \(2\min(\eta, 1-\eta)\) | \(\mathrm{TV}(p,q)\) | \(\operatorname{sign} \lambda\) | \(-D\) |
LSGAN (Mao 기타 2017년) 에서는 크리틱이 타깃 \(1\)(실제)과 \(0\)(가짜)에 회귀하는데, 이는 \(t = 2D - 1\) 아래에서 제곱 마진 손실 \(\tfrac14(1 - t)^2\) 에 해당하며 Vincze–Le Cam 발산 \(\chi^2(p \,\|\, m) = \tfrac12 \int (p-q)^2/(p+q)\) 의 4분의 1을 평가합니다. 힌지 손실 (Lim 와/과 Ye 2017년) 은 전변동 거리 \(\mathrm{TV}(p, q) = \tfrac12 \int |p - q|\) 를 평가하며 최적 크리틱은 \(\operatorname{sign} \lambda\) 를 출력합니다(\(\eta = \tfrac12\) 에서는 \([-1, 1]\) 의 임의 값이 최적입니다). 제곱 힌지 손실은 힌지 마진 및 생성자 목적 함수 \(-D(x')\) 를 공유하지만 매끄러운 연결 함수 \(\tanh(\lambda/2)\) 덕분에 \(\lambda\) 의 크기 정보를 보존합니다. 실전에서는 각 손실마다 평형 \(q = p\) 를 공유하는 비포화 생성자 목적 함수(마지막 열)를 사용합니다.
16.2.2.5 Fenchel–Young 변분 하한 (\(f\)-GAN)
식 16.2.2 에서는 \(D\) 와 \(-D\) 에 똑같은 보수를 적용하므로 베이즈 위험이 \(L(\eta) = L(1 - \eta)\) 를 만족하여 모든 분류 격차 \(\Delta_\ell(p, q)\) 는 \(p\) 와 \(q\) 에 대해 대칭이고 위로 \(L(\tfrac12)\) 에 유계입니다(5 참조). 순방향 KL 발산 \(D_{\textrm{KL}}(p \,\|\, q)\) 처럼 비대칭이거나 유계가 아닌 \(f\)-발산에 도달하려면 비대칭 보수 \(\ell_p \neq \ell_q\) 가 필요합니다.
볼록 발산 함수 \(f\) 의 볼록 켤레 함수(convex conjugate)를 \(f^*(t) = \sup_u \{ut - f(u)\}\) 라 합시다. Fenchel–Young 부등식에 의해 모든 \(u, t\) 에 대해 \(f(u) \geq ut - f^*(t)\) 이며 등호는 \(t = f'(u)\) 일 때 성립합니다. \(u = \rho(x) = p(x)/q(x)\) 와 \(t = T(x)\) 로 두고 \(q\) 아래에서 기댓값을 취하면(\(\mathbb{E}_q[\rho\, T] = \mathbb{E}_p[T]\) 이용) \(f\)-GAN (Nowozin 기타 2016년) 의 변분 하한(25.3.4절)을 얻습니다:
\[ D_f(p \,\|\, q) \;\geq\; \mathbb{E}_{x \sim p}\big[T(x)\big] - \mathbb{E}_{x' \sim q}\big[f^*(T(x'))\big]. \tag{16.2.5}\]
이 식은 \(\ell_p(t) = t\), \(\ell_q(t) = -f^*(t)\) 로 둔 식 16.2.1 의 일반 템플릿과 일치하며 최적 크리틱 \(T^\star(x) = f'(\rho(x))\) 에서 등호가 성립합니다(2 참조). 순방향 KL 발산에서는 \(f(u) = u \log u\) 가 켤레 함수 \(f^*(t) = e^{t-1}\) 과 최적 크리틱 \(T^\star(x) = 1 + \log \rho(x) = 1 + \lambda(x)\) 를 갖습니다.
16.2.2.6 실험으로 크리틱 연결 함수 검증하기
이제 로지스틱, 최소제곱, 힌지, 순방향 KL 목적 함수 아래 훈련된 크리틱들이 각각 \(\lambda(x)\) 의 이론적 연결 함수인 \(\lambda\), \(\sigma(\lambda)\), \(\operatorname{sign} \lambda\), \(1 + \lambda\) 를 학습하는지 검증합니다. 모든 곳에서 \(\lambda(x)\) 가 해석적으로 알려지도록 \(p\) 를 세 개 2차원 가우스 분포의 균등 혼합으로 정의하고 교란된 3성분 혼합 분포 \(q\) 를 구성합니다.
mu_p = np.array([[0.0, 2.4], [-2.1, -1.2], [2.1, -1.2]]) # data
A_p = np.stack([0.7 * np.eye(2)] * 3)
mu_q = np.array([[0.2, 2.6], [-2.3, -1.0], [2.0, -1.3]]) # hand-set q
A_q = np.stack([np.diag([0.8, 0.55]), np.diag([0.5, 0.6]),
np.array([[0.65, 0.2], [-0.1, 0.7]])])
def mixture_logpdf(x, mus, As):
"""Log density of the uniform mixture of Gaussians N(mu_k, A_k^T A_k)."""
comps = []
for mu, A in zip(mus, As):
Sigma, diff = A.T @ A, x - mu
sol = np.linalg.solve(Sigma, diff.T).T
comps.append(-0.5 * ((diff * sol).sum(1)
+ np.linalg.slogdet(2 * np.pi * Sigma)[1]))
return np.logaddexp.reduce(np.stack(comps) - np.log(len(mus)), axis=0)
def sample_mixture(n, mus, As, rng):
"""n draws from the uniform mixture of Gaussians mu_k + z A_k."""
k = rng.integers(0, len(mus), n)
z = rng.standard_normal((n, 2))
return np.einsum('ni,nij->nj', z, As[k]) + mus[k]
mu_p = np.array([[0.0, 2.4], [-2.1, -1.2], [2.1, -1.2]]) # data
A_p = np.stack([0.7 * np.eye(2)] * 3)
mu_q = np.array([[0.2, 2.6], [-2.3, -1.0], [2.0, -1.3]]) # hand-set q
A_q = np.stack([np.diag([0.8, 0.55]), np.diag([0.5, 0.6]),
np.array([[0.65, 0.2], [-0.1, 0.7]])])
def mixture_logpdf(x, mus, As):
"""Log density of the uniform mixture of Gaussians N(mu_k, A_k^T A_k)."""
comps = []
for mu, A in zip(mus, As):
Sigma, diff = A.T @ A, x - mu
sol = np.linalg.solve(Sigma, diff.T).T
comps.append(-0.5 * ((diff * sol).sum(1)
+ np.linalg.slogdet(2 * np.pi * Sigma)[1]))
return np.logaddexp.reduce(np.stack(comps) - np.log(len(mus)), axis=0)
def sample_mixture(n, mus, As, rng):
"""n draws from the uniform mixture of Gaussians mu_k + z A_k."""
k = rng.integers(0, len(mus), n)
z = rng.standard_normal((n, 2))
return np.einsum('ni,nij->nj', z, As[k]) + mus[k]고정된 격자 위에서 구적법을 쓰면 이 형태를 가진 임의 혼합 분포 \(q\) 에 대해 \(\mathrm{JS}(p, q)\) 를 얻습니다. 이 절 뒷부분에서는 똑같은 함수가 매 스텝 훈련된 생성자를 채점합니다.
grid_1d = np.linspace(-7.0, 7.0, 281)
grid_2d = np.stack([g.ravel() for g in np.meshgrid(grid_1d, grid_1d)], axis=1)
cell_area = (grid_1d[1] - grid_1d[0]) ** 2
def js_mixtures(mus_q, As_q, mus_p=mu_p, As_p=A_p):
"""JS(p, q) between two known mixtures, p the data by default, by
quadrature on grid_2d."""
logp = mixture_logpdf(grid_2d, mus_p, As_p)
logq = mixture_logpdf(grid_2d, mus_q, As_q)
p, q = np.exp(logp), np.exp(logq)
logm = np.log(np.maximum((p + q) / 2, 1e-300))
return 0.5 * (p * (logp - logm) + q * (logq - logm)).sum() * cell_area
print(f'JS(p, q) for the hand-set q: {js_mixtures(mu_q, A_q):.3f} nats')JS(p, q) for the hand-set q: 0.033 nats
grid_1d = np.linspace(-7.0, 7.0, 281)
grid_2d = np.stack([g.ravel() for g in np.meshgrid(grid_1d, grid_1d)], axis=1)
cell_area = (grid_1d[1] - grid_1d[0]) ** 2
def js_mixtures(mus_q, As_q, mus_p=mu_p, As_p=A_p):
"""JS(p, q) between two known mixtures, p the data by default, by
quadrature on grid_2d."""
logp = mixture_logpdf(grid_2d, mus_p, As_p)
logq = mixture_logpdf(grid_2d, mus_q, As_q)
p, q = np.exp(logp), np.exp(logq)
logm = np.log(np.maximum((p + q) / 2, 1e-300))
return 0.5 * (p * (logp - logm) + q * (logq - logm)).sum() * cell_area
print(f'JS(p, q) for the hand-set q: {js_mixtures(mu_q, A_q):.3f} nats')JS(p, q) for the hand-set q: 0.033 nats
수동으로 설정한 \(q\) 는 데이터로부터 백분의 몇 nat 떨어져 있어 훈련 후반부 생성자가 마주하는 수준의 불일치를 나타냅니다. 크리틱은 64유닛 은닉층 두 개를 가진 작은 Leaky ReLU 신경망입니다.
TRUNC_STD = 0.8796 # standard deviation of N(0, 1) truncated at +-2
def make_critic():
"""Leaky-ReLU MLP with LeCun-normal weights and zero biases."""
D = nn.Sequential(nn.Linear(2, 64), nn.LeakyReLU(0.2),
nn.Linear(64, 64), nn.LeakyReLU(0.2), nn.Linear(64, 1))
for layer in D[::2]: # weight std 1/sqrt(fan_in) after truncation
s = layer.in_features ** -0.5 / TRUNC_STD
nn.init.trunc_normal_(layer.weight, std=s, a=-2 * s, b=2 * s)
nn.init.zeros_(layer.bias)
return D
def make_critic(rngs):
"""Leaky-ReLU MLP; nnx.Linear gives LeCun-normal weights, zero biases."""
leaky = lambda x: nnx.leaky_relu(x, 0.2)
return nnx.Sequential(nnx.Linear(2, 64, rngs=rngs), leaky,
nnx.Linear(64, 64, rngs=rngs), leaky,
nnx.Linear(64, 1, rngs=rngs))각 손실은 실제 배치 점수 r와 생성 배치 점수 f 위에 적은 표 16.2.2 의 크리틱 손실과 생성자 손실 쌍으로 저장됩니다.
losses = { # name: (critic loss, generator loss), both on the scores r, f
'logistic': (lambda r, f: (softplus(-r) + softplus(f)).mean(),
lambda r, f: softplus(-f).mean()),
'least squares': (lambda r, f: ((r - 1) ** 2 + f ** 2).mean() / 2,
lambda r, f: ((f - 1) ** 2).mean() / 2),
'hinge': (lambda r, f: (relu(1 - r) + relu(1 + f)).mean(),
lambda r, f: -f.mean()),
'squared hinge': (lambda r, f: (relu(1 - r) ** 2 + relu(1 + f) ** 2).mean(),
lambda r, f: -f.mean()),
}losses = { # name: (critic loss, generator loss), both on the scores r, f
'logistic': (lambda r, f: (softplus(-r) + softplus(f)).mean(),
lambda r, f: softplus(-f).mean()),
'least squares': (lambda r, f: ((r - 1) ** 2 + f ** 2).mean() / 2,
lambda r, f: ((f - 1) ** 2).mean() / 2),
'hinge': (lambda r, f: (relu(1 - r) + relu(1 + f)).mean(),
lambda r, f: -f.mean()),
'squared hinge': (lambda r, f: (relu(1 - r) ** 2 + relu(1 + f) ** 2).mean(),
lambda r, f: -f.mean()),
}연결 함수는 고정된 \(q\) 에 대한 최적 반응을 기술하므로 수동 설정한 \(q\) 에 맞서 세 손실 아래 각각 새 크리틱을 훈련하고, 네 번째 크리틱은 순방향 KL 하한 \(\mathbb{E}_p[T] - \mathbb{E}_q[e^{T-1}]\) 을 최대화하도록 훈련합니다.
to_t = lambda a: torch.tensor(a, dtype=torch.float32)
def best_response(critic_loss, seed=0, steps=3000, batch=512, lr=1e-3):
"""Fresh critic trained against the fixed q, as a NumPy function."""
rng = np.random.default_rng(seed)
torch.manual_seed(seed)
D = make_critic()
opt = torch.optim.Adam(D.parameters(), lr)
for _ in range(steps):
X = to_t(sample_mixture(batch, mu_p, A_p, rng))
Y = to_t(sample_mixture(batch, mu_q, A_q, rng))
opt.zero_grad()
critic_loss(D(X), D(Y)).backward()
opt.step()
return lambda x: D(to_t(x)).squeeze(-1).detach().numpy()
kl_dual = lambda r, f: -(r.mean() - torch.exp(f - 1).mean())
critics = {name: best_response(losses[name][0])
for name in ('logistic', 'least squares', 'hinge')}
critics['forward KL'] = best_response(kl_dual)@nnx.jit(static_argnums=0)
def best_response_step(critic_loss, D, opt, X, Y):
opt.update(D, nnx.grad(lambda D_: critic_loss(D_(X), D_(Y)))(D))
def best_response(critic_loss, seed=0, steps=3000, batch=512, lr=1e-3):
"""Fresh critic trained against the fixed q, as a NumPy function."""
rng = np.random.default_rng(seed)
D = make_critic(nnx.Rngs(seed))
opt = nnx.Optimizer(D, optax.adam(lr), wrt=nnx.Param)
for _ in range(steps):
X = jnp.asarray(sample_mixture(batch, mu_p, A_p, rng), jnp.float32)
Y = jnp.asarray(sample_mixture(batch, mu_q, A_q, rng), jnp.float32)
best_response_step(critic_loss, D, opt, X, Y)
return lambda x: np.asarray(D(jnp.asarray(x, jnp.float32))).squeeze(-1)
kl_dual = lambda r, f: -(r.mean() - jnp.exp(f - 1).mean())
critics = {name: best_response(losses[name][0])
for name in ('logistic', 'least squares', 'hinge')}
critics['forward KL'] = best_response(kl_dual)\(p\) 에서 뽑은 점 300개와 \(q\) 에서 뽑은 점 300개에서 훈련된 각 크리틱을 평가하여 이론적 연결 함수(파선 곡선)와 함께 참 로그 밀도비 \(\lambda(x)\) 에 대한 출력을 그립니다.
rng = np.random.default_rng(7)
pts = np.concatenate([sample_mixture(300, mu_p, A_p, rng),
sample_mixture(300, mu_q, A_q, rng)])
lam = mixture_logpdf(pts, mu_p, A_p) - mixture_logpdf(pts, mu_q, A_q)
lam_line = np.linspace(lam.min(), lam.max(), 200)
links = {'logistic': lambda l: l, 'least squares': lambda l: 1 / (1 + np.exp(-l)),
'hinge': np.sign, 'forward KL': lambda l: 1 + l}
fig, axes = d2l.plt.subplots(1, 4, figsize=(12, 3))
for ax, (name, link) in zip(axes, links.items()):
out = critics[name](pts)
d2l.plot([lam[:300], lam[300:], lam_line],
[out[:300], out[300:], link(lam_line)], xlabel=r'$\lambda$',
fmts=('.', '.', 'k--'), axes=ax,
legend=['x ~ p', "x' ~ q", 'link'] if name == 'logistic' else None)
ax.set_title(name)
axes[0].set_ylabel('critic output')
fig.tight_layout()rng = np.random.default_rng(7)
pts = np.concatenate([sample_mixture(300, mu_p, A_p, rng),
sample_mixture(300, mu_q, A_q, rng)])
lam = mixture_logpdf(pts, mu_p, A_p) - mixture_logpdf(pts, mu_q, A_q)
lam_line = np.linspace(lam.min(), lam.max(), 200)
links = {'logistic': lambda l: l, 'least squares': lambda l: 1 / (1 + np.exp(-l)),
'hinge': np.sign, 'forward KL': lambda l: 1 + l}
fig, axes = d2l.plt.subplots(1, 4, figsize=(12, 3))
for ax, (name, link) in zip(axes, links.items()):
out = critics[name](pts)
d2l.plot([lam[:300], lam[300:], lam_line],
[out[:300], out[300:], link(lam_line)], xlabel=r'$\lambda$',
fmts=('.', '.', 'k--'), axes=ax,
legend=['x ~ p', "x' ~ q", 'link'] if name == 'logistic' else None)
ax.set_title(name)
axes[0].set_ylabel('critic output')
fig.tight_layout()네 신경망 모두 \(\lambda(x)\) 의 예측된 이론적 연결 함수인 항등 함수 \(\lambda\), 시그모이드 \(\sigma(\lambda)\), 계단 함수 \(\operatorname{sign} \lambda\), 이동된 항등 함수 \(1 + \lambda\) 를 잘 추적합니다. \([-1, 1]\) 안의 어떤 출력이든 최소 조건부 위험을 달성하는 \(\lambda = 0\) 부근에서 힌지 크리틱의 산포가 더 넓어지는 점에 주목합시다.
16.2.3 적분 확률 거리
\(f\)-발산이 비제약 크리틱을 비선형 보수와 짝짓는 반면, 적분 확률 거리(integral probability metric, IPM)는 선형 보수 \(\ell_p(t) = t\) 와 \(\ell_q(t) = -t\) 를 쓰면서 크리틱을 대칭 함수족 \(\mathcal{F}\) 로 제한합니다(25.4.1절):
\[ d_{\mathcal{F}}(p, q) \;=\; \sup_{T \in \mathcal{F}} \Big\{ \mathbb{E}_{x \sim p}\big[T(x)\big] - \mathbb{E}_{x' \sim q}\big[T(x')\big] \Big\}. \tag{16.2.6}\]
\(\mathcal{F}\) 에 제약이 없다면 임의의 양의 상수로 \(T\) 를 스케일링할 때 \(p \neq q\) 인 모든 경우 기댓값 차이가 \(+\infty\) 로 발산할 것입니다. \(\mathcal{F}\) 가 매끄러운 함수들로 이루어져 있을 때 \(d_{\mathcal{F}}(p, q)\) 는 단순한 점별 비율 \(p(x)/q(x)\) 가 아니라 공간 \(\mathcal{X}\) 의 기하학적 구조에 의존합니다.
16.2.3.1 최대 평균 불일치 (MMD)
대역폭 \(s\) 인 가우스 RBF 커널 \(k(x, x') = \exp(-\|x - x'\|^2/(2s^2))\) 같은 양의 정부호 커널 \(k(x, x')\) 가 주어졌을 때 \(\mathcal{F}\) 를 \(k\) 에 대응하는 재생 커널 힐베르트 공간(RKHS)의 단위 공으로 택하면 최대 평균 불일치(Maximum Mean Discrepancy, MMD) (Gretton 기타 2012년) (25.4.1절)를 얻으며, 그 제곱값은 쌍별 커널 기댓값들로 이루어진 닫힌 형태를 갖습니다:
\[ \begin{aligned} \mathrm{MMD}^2(p, q) &= \mathbb{E}_{x, \tilde x \sim p}\big[k(x, \tilde x)\big] + \mathbb{E}_{x', \tilde x' \sim q}\big[k(x', \tilde x')\big] \\ &\quad - 2\, \mathbb{E}_{x \sim p,\, x' \sim q}\big[k(x, x')\big]. \end{aligned} \tag{16.2.7}\]
스케일링 차이를 제외한 최적 검정 함수는 한 점과 \(p\) 의 평균 유사도 및 \(q\) 의 평균 유사도 차이를 재는 증인 함수(witness function) \(w(x) = \mathbb{E}_{\tilde x \sim p}[k(x, \tilde x)] - \mathbb{E}_{\tilde x' \sim q}[k(x, \tilde x')]\) 입니다. 식 16.2.7 에는 크리틱 신경망이 전혀 필요 없으므로 생성자가 불편 유한 표본 추정량 mmd2_unbiased(16.5절 에서 KID 계산에도 사용됨)를 직접 최소화할 수 있습니다.
def mmd2_unbiased(K_pp, K_qq, K_pq):
"""Unbiased MMD^2 from the kernel matrices within p, within q, and
across; the diagonals (a point with itself) are left out."""
m, n = len(K_pp), len(K_qq)
return ((K_pp.sum() - K_pp.diagonal().sum()) / (m * (m - 1))
+ (K_qq.sum() - K_qq.diagonal().sum()) / (n * (n - 1))
- 2 * K_pq.mean())
def mmd2_unbiased(K_pp, K_qq, K_pq):
"""Unbiased MMD^2 from the kernel matrices within p, within q, and
across; the diagonals (a point with itself) are left out."""
m, n = len(K_pp), len(K_qq)
return ((K_pp.sum() - K_pp.diagonal().sum()) / (m * (m - 1))
+ (K_qq.sum() - K_qq.diagonal().sum()) / (n * (n - 1))
- 2 * K_pq.mean())16.2.3.2 Wasserstein-1 거리 (\(W_1\))
\(\mathcal{F}\) 를 1-립시츠(1-Lipschitz) 함수족(모든 \(x, y\) 에 대해 \(|T(x) - T(y)| \leq \|x - y\|\))으로 택하면 Kantorovich–Rubinstein 쌍대성(25.4.2절)에 의해 Wasserstein-1 거리(또는 땅파기 거리, Earth Mover’s distance)를 얻습니다:
\[ W_1(p, q) \;=\; \inf_{\pi \in \Pi(p, q)} \mathbb{E}_{(x, x') \sim \pi}\big[\|x - x'\|\big], \]
여기서 \(\Pi(p, q)\) 는 주변 분포가 \(p\) 와 \(q\) 인 결합 수송 계획들의 집합입니다. 최적 1-립시츠 크리틱(Kantorovich 퍼텐셜)은 \(q\) 에서 \(p\) 로 향하는 최적 수송 반직선들을 따라 단위 그레이디언트 노름을 갖습니다. 1차원에서는 \(W_1(p, q) = \int_{-\infty}^\infty |F_p(t) - F_q(t)|\,dt\) 이므로 분포를 \(\mu\) 만큼 이동시키면 얼마나 멀리 떨어져 있든 일정한 단위 기울기로 \(W_1(p, q) = |\mu|\) 가 됩니다.
고차원에서 Wasserstein GAN(WGAN)은 주로 세 가지 메커니즘을 통해 신경망 크리틱 \(T\) 에 대한 1-립시츠 제약을 근사합니다:
- 가중치 클리핑 (Arjovsky 기타 2017년) 은 용량이 제한되는 대가를 치르고 가중치를 \([-c, c]\) 로 클램핑하여 아키텍처에 의존하는 상수 \(\kappa\) 에 대한 \(\kappa\)-립시츠성을 강제합니다.
- 그레이디언트 페널티(WGAN-GP) (Gulrajani 기타 2017년) 는 실제 샘플과 생성 샘플 사이의 무작위 보간점 \(\tilde x = u x + (1-u)x'\) 에서 \(\gamma\,\mathbb{E}[(\|\nabla_x T(\tilde x)\| - 1)^2]\) 를 더합니다.
- 스펙트럼 정규화 (Miyato 기타 2018년) 는 각 가중치 행렬을 최대 특잇값 \(\sigma_{\max}(W)\) 로 나누어 모든 선형 층의 립시츠 상수를 \(1\) 이하로 묶어 둡니다.
힌지 손실이 두 부류를 잇는 다리 역할을 한다는 점에 주목합시다. \(|D(x)| \leq 1\) 일 때 보수가 선형이므로 비제약 힌지 크리틱은 \(|D(x)| \leq 1\) 로 유계인 함수들 위의 IPM에 해당합니다(\(2\,\mathrm{TV}(p, q) - 2\) 평가). SAGAN이나 BigGAN처럼 힌지 손실을 스펙트럼 정규화와 결합해 \(D\) 를 유계이면서 \(\kappa\)-립시츠로 만들면 포화되기 전 분리 거리 \(2/\kappa\) 까지 \(\kappa\,W_1\) 처럼 선형으로 자라나는 크리틱을 얻습니다.
16.2.3.3 고차원 표본 복잡도
고정 커널 MMD와 경험적 \(W_1\) 은 표본 복잡도에서 극명하게 갈립니다. 불편 \(\mathrm{MMD}^2\) 추정량은 차원에 무관한 속도 \(O(n^{-1/2})\) 로 수렴하는 반면 (Gretton 기타 2012년) (다만 고정 커널 아래 주어진 이동량의 추정 대상 \(\mathrm{MMD}^2\) 자체는 차원이 커질 때 작아질 수 있음 (Ramdas 기타 2015년)), 차원 \(d_x > 2\) 에서 플러그인 경험적 \(W_1\) 거리는 속도 \(O(n^{-1/d_x})\) 로 차원의 저주를 겪습니다 (Weed 와/과 Bach 2019년). 한편 변분 \(f\)-발산 추정량들은 \(\rho = p/q\) 가 클 때 높은 분산에 시달릴 수 있습니다. 예를 들어 순방향 KL 쌍대 하한에서 \(q\) 아래 \(e^{T^\star(x') - 1} = \rho(x')\) 의 분산은 \(\chi^2(p \,\|\, q)\) 와 같은데 이는 \(D_{\textrm{KL}}(p \,\|\, q) < \infty\) 일 때도 발산할 수 있습니다(4 참조).
16.2.4 데이터에서 멀 때와 가까울 때의 그레이디언트
16.2.4.1 분리 거리에 따른 발산 기울기
두 분포가 멀어질 때 모집단 발산들이 어떻게 거동하는지 보기 위해 분리 거리 \(\mu > 0\) 의 함수로 \(p = \mathcal{N}(0, 1)\) 과 \(q = \mathcal{N}(\mu, 1)\) 을 살펴봅시다. 여기서 \(W_1(p, q) = \mu\) 는 상수 도함수 \(1\) 을 갖고, \(\mathrm{JS}(p, q)\) 는 수치 적분으로 구할 수 있으며, 대역폭 \(s\) 인 가우스 RBF 커널 아래 \(\mathrm{MMD}^2(p, q)\) 는 정확한 가우스 적분 공식을 갖습니다:
\[ \mathrm{MMD}^2(p, q) \;=\; \frac{2s}{\sqrt{s^2 + 2}} \left( 1 - \exp\!\left( -\frac{\mu^2}{2(s^2 + 2)} \right) \right), \tag{16.2.8}\]
\(\mu\) 에 대한 이 식의 도함수는 \(\mu = \sqrt{s^2 + 2}\)(\(s = 4\) 일 때 \(\approx 4.2\))에서 정점을 찍은 뒤 \(e^{-\mu^2/(2(s^2+2))}\) 처럼 감쇠합니다.
xs = np.linspace(-10.0, 30.0, 8001) # fixed quadrature grid
def normal_pdf(x, mu, sigma=1.0):
return np.exp(-(x - mu) ** 2 / (2 * sigma ** 2)) / np.sqrt(
2 * np.pi * sigma ** 2)
def js_gap(p, q):
"""log 2 - JS(p, q) on xs, accurate even when tiny: the integral of
(p log(1 + q/p) + q log(1 + p/q)) / 2, with log(1 + e^a) computed as
logaddexp(0, a)."""
a = np.log(q) - np.log(p)
return 0.5 * np.trapezoid(p * np.logaddexp(0, a) + q * np.logaddexp(0, -a),
xs)
def js_1d(p, q):
return np.log(2) - js_gap(p, q)
s = 4.0 # RBF kernel bandwidth
mus = np.linspace(0.1, 20.0, 200) # separations mu
gaps = np.array([js_gap(normal_pdf(xs, 0.0), normal_pdf(xs, mu))
for mu in mus])
mmd2 = 2 * s / np.sqrt(s ** 2 + 2) * (1 - np.exp(-mus ** 2
/ (2 * (s ** 2 + 2))))
slopes = [-np.gradient(gaps, mus), np.gradient(mmd2, mus),
np.ones_like(mus)] # W1 = |mu| has slope one
for mu in (1.0, 7.0, 20.0):
js = js_1d(normal_pdf(xs, 0.0), normal_pdf(xs, mu))
print(f'mu = {mu:2.0f}: JS slope {np.interp(mu, mus, slopes[0]):.4g}, '
f'JS / log 2 = {js / np.log(2):.4f}, '
f'MMD^2 slope {np.interp(mu, mus, slopes[1]):.4g}')
peak = slopes[1].argmax()
print(f'MMD^2 slope peaks at mu = {mus[peak]:.1f} with {slopes[1][peak]:.3f}')
d2l.plot(mus, slopes, xlabel=r'separation $\mu$', ylabel='slope',
legend=['JS', 'MMD$^2$', '$W_1$'], yscale='log', figsize=(5, 3))mu = 1: JS slope 0.1987, JS / log 2 = 0.1607, MMD^2 slope 0.1019
mu = 7: JS slope 0.001264, JS / log 2 = 0.9990, MMD^2 slope 0.188
mu = 20: JS slope 1.549e-22, JS / log 2 = 1.0000, MMD^2 slope 3.303e-05
MMD^2 slope peaks at mu = 4.2 with 0.269
xs = np.linspace(-10.0, 30.0, 8001) # fixed quadrature grid
def normal_pdf(x, mu, sigma=1.0):
return np.exp(-(x - mu) ** 2 / (2 * sigma ** 2)) / np.sqrt(
2 * np.pi * sigma ** 2)
def js_gap(p, q):
"""log 2 - JS(p, q) on xs, accurate even when tiny: the integral of
(p log(1 + q/p) + q log(1 + p/q)) / 2, with log(1 + e^a) computed as
logaddexp(0, a)."""
a = np.log(q) - np.log(p)
return 0.5 * np.trapezoid(p * np.logaddexp(0, a) + q * np.logaddexp(0, -a),
xs)
def js_1d(p, q):
return np.log(2) - js_gap(p, q)
s = 4.0 # RBF kernel bandwidth
mus = np.linspace(0.1, 20.0, 200) # separations mu
gaps = np.array([js_gap(normal_pdf(xs, 0.0), normal_pdf(xs, mu))
for mu in mus])
mmd2 = 2 * s / np.sqrt(s ** 2 + 2) * (1 - np.exp(-mus ** 2
/ (2 * (s ** 2 + 2))))
slopes = [-np.gradient(gaps, mus), np.gradient(mmd2, mus),
np.ones_like(mus)] # W1 = |mu| has slope one
for mu in (1.0, 7.0, 20.0):
js = js_1d(normal_pdf(xs, 0.0), normal_pdf(xs, mu))
print(f'mu = {mu:2.0f}: JS slope {np.interp(mu, mus, slopes[0]):.4g}, '
f'JS / log 2 = {js / np.log(2):.4f}, '
f'MMD^2 slope {np.interp(mu, mus, slopes[1]):.4g}')
peak = slopes[1].argmax()
print(f'MMD^2 slope peaks at mu = {mus[peak]:.1f} with {slopes[1][peak]:.3f}')
d2l.plot(mus, slopes, xlabel=r'separation $\mu$', ylabel='slope',
legend=['JS', 'MMD$^2$', '$W_1$'], yscale='log', figsize=(5, 3))mu = 1: JS slope 0.1987, JS / log 2 = 0.1607, MMD^2 slope 0.1019
mu = 7: JS slope 0.001264, JS / log 2 = 0.9990, MMD^2 slope 0.188
mu = 20: JS slope 1.549e-22, JS / log 2 = 1.0000, MMD^2 slope 3.303e-05
MMD^2 slope peaks at mu = 4.2 with 0.269
그래프 및 그림 16.2.1 에서 보듯이 \(\mathrm{JS}(p, q)\) 의 도함수는 \(\mu = 7\) 무렵 두 자릿수 넘게 떨어지고(\(\mu = 1\) 에서의 \(0.20\) 대 \(0.0013\)) \(\mu = 20\) 에서는 \(1.5 \times 10^{-22}\) 에 이릅니다. 이와 대조적으로 \(W_1\) 은 모든 거리에서 단위 기울기를 유지하며 \(\mathrm{MMD}^2\) 는 커널 대역폭 \(s\) 정도 크기의 분리 거리까지 강한 그레이디언트를 유지합니다.
16.2.4.2 분리된 출발점에서의 훈련된 크리틱
이론적 발산 곡선들은 모든 가측 함수 위의 최적 크리틱을 가정합니다. 실전에서 크리틱은 생성자 업데이트당 몇 스텝만 훈련되는 유한 신경망입니다. 멀리 떨어진 초기화에서 훈련된 크리틱들이 어떻게 거동하는지 시험하기 위해 생성자 스텝당 5회 갱신되는 은닉층 2개짜리 ReLU 크리틱에 맞서 기본 SGD(스텝 크기가 그레이디언트 크기를 직접 반영하도록)로 \(\theta\) 를 갱신하며 \(\theta_0 = 6\) 에서 출발하는 1차원 위치 생성자 \(q_\theta = \mathcal{N}(\theta, 1)\)(\(x' = \theta + z\))을 \(p = \mathcal{N}(0, 1)\) 에 적합해 봅니다.
def mmd2_loss(x, y, bandwidths=(0.5, 1.0, 2.0)):
"""Unbiased MMD^2 under the sum of RBF kernels of the given bandwidths."""
def kernel(a, b):
sq_dist = torch.cdist(a, b) ** 2
return sum(torch.exp(-sq_dist / (2 * s ** 2)) for s in bandwidths)
return mmd2_unbiased(kernel(x, x), kernel(y, y), kernel(x, y))
def mmd2_median(x, y):
"""MMD^2 with one RBF kernel, its bandwidth the median pairwise distance
of the pooled batch, held constant in the gradient."""
xy = torch.cat([x, y])
return mmd2_loss(x, y, (torch.cdist(xy, xy).median().detach(),))
def gradient_penalty(D, X, fake, u, one_sided=False):
"""Mean (|D'(x)| - 1)^2 at the points u X + (1 - u) fake (inputs 1-D);
one-sided, only slopes steeper than one pay: max(0, |D'(x)| - 1)^2."""
x = (u * X + (1 - u) * fake).requires_grad_()
grad, = torch.autograd.grad(D(x).sum(), x, create_graph=True)
excess = grad.abs() - 1
return ((excess.clamp(min=0) if one_sided else excess) ** 2).mean()def mmd2_loss(x, y, bandwidths=(0.5, 1.0, 2.0)):
"""Unbiased MMD^2 under the sum of RBF kernels of the given bandwidths."""
def kernel(a, b):
sq_dist = ((a[:, None] - b[None]) ** 2).sum(-1)
return sum(jnp.exp(-sq_dist / (2 * s ** 2)) for s in bandwidths)
return mmd2_unbiased(kernel(x, x), kernel(y, y), kernel(x, y))
def mmd2_median(x, y):
"""MMD^2 with one RBF kernel, its bandwidth the median pairwise distance
of the pooled batch, held constant in the gradient."""
xy = jnp.concatenate([x, y])
dist = jnp.sqrt(((xy[:, None] - xy[None]) ** 2).sum(-1))
return mmd2_loss(x, y, (jax.lax.stop_gradient(jnp.median(dist)),))
def gradient_penalty(D, X, fake, u, one_sided=False):
"""Mean (|D'(x)| - 1)^2 at the points u X + (1 - u) fake (inputs 1-D);
one-sided, only slopes steeper than one pay: max(0, |D'(x)| - 1)^2."""
grad = jax.grad(lambda x: D(x).sum())(u * X + (1 - u) * fake)
excess = jnp.abs(grad) - 1
return ((jnp.maximum(excess, 0) if one_sided else excess) ** 2).mean()train_shift는 크리틱이 최적 반응 근처에 머물도록 생성자 스텝마다 크리틱에 다섯 번의 Adam 스텝을 부여합니다. 생성자는 학습률 \(0.01\) 의 단순 경사 스텝을 밟는데, Adam을 쓰면 모든 스텝이 대략 학습률 크기로 재스케일링되어 확인하고자 하는 그레이디언트 크기가 가려지기 때문입니다. 이 함수는 매 스텝 \(\theta\) 와 생성자 그레이디언트를 기록합니다. 양수 gp는 크리틱 손실에 그레이디언트 페널티를 더하고 one_sided=True는 1보다 가파른 기울기에만 \(\max(0, |T'| - 1)^2\) 을 부과하며, critic_loss를 None으로 두면 생성자가 두 배치의 gen_loss를 직접 최소화합니다.
class Shift(nn.Module):
"""The generator x' = theta + z."""
def __init__(self, theta0):
super().__init__()
self.theta = nn.Parameter(torch.tensor(theta0))
def forward(self, z):
return self.theta + z
def train_shift(critic_loss, gen_loss, seed, gp=0.0, one_sided=False,
theta0=6.0, steps=1500, n_critic=5, batch=256, lr_D=1e-2,
lr_G=1e-2):
"""Fit x' = theta + z to N(0, 1) by plain gradient steps on theta; return
theta0 and theta after every step, the gradient of every step, and the
critic."""
rng = np.random.default_rng(seed)
torch.manual_seed(seed)
G, D = Shift(theta0), d2l.make_mlp([1, 32, 32, 1], nn.ReLU())
opt_G = torch.optim.SGD(G.parameters(), lr_G)
opt_D = torch.optim.Adam(D.parameters(), lr_D, betas=(0.5, 0.9))
n = n_critic if critic_loss else 0
thetas, grads = [theta0], []
for _ in range(steps):
X, Z = (to_t(rng.standard_normal((n + 1, batch, 1))) for _ in range(2))
U = to_t(rng.uniform(size=(n, batch, 1))) # interpolation weights
for i in range(n):
fake = G(Z[i]).detach()
loss = critic_loss(D(X[i]), D(fake))
if gp:
loss = loss + gp * gradient_penalty(D, X[i], fake, U[i],
one_sided)
opt_D.zero_grad()
loss.backward()
opt_D.step()
fake = G(Z[-1])
loss = (gen_loss(X[-1], fake) if critic_loss is None
else gen_loss(D(X[-1]), D(fake)))
opt_G.zero_grad()
loss.backward()
grads.append(G.theta.grad.item())
opt_G.step()
thetas.append(G.theta.item())
return np.array(thetas), np.array(grads), D
class Shift(nnx.Module):
"""The generator x' = theta + z."""
def __init__(self, theta0):
self.theta = nnx.Param(jnp.array(theta0))
def __call__(self, z):
return self.theta + z
@nnx.jit(static_argnums=(0, 1, 2, 3))
def shift_step(critic_loss, gen_loss, gp, one_sided, G, D, opt_G, opt_D, X, Z,
U):
"""One critic step per row of U, then one generator step; returns the
generator's gradient."""
for i in range(len(U)):
fake = G(Z[i])
def d_loss(D_):
loss = critic_loss(D_(X[i]), D_(fake))
if gp:
loss = loss + gp * gradient_penalty(D_, X[i], fake, U[i],
one_sided)
return loss
opt_D.update(D, nnx.grad(d_loss)(D))
def g_loss(G_):
fake = G_(Z[-1])
return (gen_loss(X[-1], fake) if critic_loss is None
else gen_loss(D(X[-1]), D(fake)))
grad = nnx.grad(g_loss)(G)
opt_G.update(G, grad)
return grad.theta[...]
def train_shift(critic_loss, gen_loss, seed, gp=0.0, one_sided=False,
theta0=6.0, steps=1500, n_critic=5, batch=256, lr_D=1e-2,
lr_G=1e-2):
"""Fit x' = theta + z to N(0, 1) by plain gradient steps on theta; return
theta0 and theta after every step, the gradient of every step, and the
critic."""
rng = np.random.default_rng(seed)
G = Shift(theta0)
D = d2l.make_mlp([1, 32, 32, 1], nnx.relu, rngs=nnx.Rngs(seed))
opt_G = nnx.Optimizer(G, optax.sgd(lr_G), wrt=nnx.Param)
opt_D = nnx.Optimizer(D, optax.adam(lr_D, 0.5, 0.9), wrt=nnx.Param)
n = n_critic if critic_loss else 0
thetas, grads = [theta0], []
for _ in range(steps):
X, Z = (jnp.asarray(rng.standard_normal((n + 1, batch, 1)),
jnp.float32) for _ in range(2))
U = jnp.asarray(rng.uniform(size=(n, batch, 1)), jnp.float32)
grad = shift_step(critic_loss, gen_loss, gp, one_sided, G, D, opt_G,
opt_D, X, Z, U)
grads.append(grad) # device scalars,
thetas.append(G.theta[...]) # converted once below
return np.asarray(jnp.stack(thetas)), np.asarray(jnp.stack(grads)), D각각 세 시드에 걸쳐 여섯 가지 구성을 비교합니다. 포화 로지스틱, 비포화 로지스틱, 힌지, WGAN-GP(\(\gamma = 10\), 양측 페널티 \((|T'| - 1)^2\)), 단측 페널티 \(\max(0, |T'| - 1)^2\) 를 쓴 WGAN-GP, 그리고 중앙값 대역폭 MMD입니다. 각 실행마다 첫 100스텝 동안의 생성자 그레이디언트 크기 중앙값, \(\theta\) 의 궤적, 도착(arrival) 스텝(\(|\theta| < 0.5\) 에 처음 도달하는 스텝), 도착 이후 최대 이탈(farthest excursion) \(\max |\theta|\) 를 보고합니다.
w1 = (lambda r, f: f.mean() - r.mean(), lambda r, f: -f.mean())
arms = {'logistic, sat.': (losses['logistic'][0],
lambda r, f: -softplus(f).mean(), {}),
'logistic, NS': (*losses['logistic'], {}),
'hinge': (*losses['hinge'], {}),
'W1 + GP': (*w1, dict(gp=10.0)),
'W1 + 1-sided GP': (*w1, dict(gp=10.0, one_sided=True)),
'MMD, median': (None, mmd2_median, {})}
steps, w1_runs = (0, 100, 300, 1000, 1500), [] # (arm, seed, theta, critic)
print(f'{"":17s}|grad| theta at steps {", ".join(map(str, steps))}'
' arrival farthest')
for name, (critic_loss, gen_loss, kwargs) in arms.items():
for seed in range(3):
thetas, grads, D = train_shift(critic_loss, gen_loss, seed, **kwargs)
if name.startswith('W1'):
w1_runs.append((name, seed, thetas[-1], D))
hit = np.flatnonzero(np.abs(thetas) < 0.5) # arrival: hit[0]
print(f'{name:16s}{seed}{np.median(np.abs(grads[:100])):7.3f} '
+ ''.join(f'{thetas[t]:7.2f}' for t in steps)
+ (f'{hit[0]:9d}{np.abs(thetas[hit[0]:]).max():10.2f}'
if len(hit) else ' not reached')) |grad| theta at steps 0, 100, 300, 1000, 1500 arrival farthest
logistic, sat. 0 0.007 6.00 5.99 5.96 5.85 5.77 not reached
logistic, sat. 1 0.009 6.00 5.98 5.95 5.85 5.76 not reached
logistic, sat. 2 0.015 6.00 5.98 5.96 5.85 5.77 not reached
logistic, NS 0 2.812 6.00 3.30 0.79 0.03 0.00 383 0.50
logistic, NS 1 2.876 6.00 3.26 0.78 0.02 0.00 380 0.50
logistic, NS 2 2.730 6.00 3.35 0.80 0.02 0.00 388 0.50
hinge 0 1.451 6.00 4.64 3.31 0.02 0.04 812 0.49
hinge 1 1.558 6.00 4.50 3.50 0.00 -0.04 874 0.50
hinge 2 1.278 6.00 4.81 3.51 -0.06 -0.00 918 0.50
W1 + GP 0 1.262 6.00 4.74 2.39 0.30 0.30 477 1.48
W1 + GP 1 1.263 6.00 4.89 2.52 -4.13 -7.18 487 7.49
W1 + GP 2 1.252 6.00 4.97 2.60 -4.08 -7.61 495 7.61
W1 + 1-sided GP 0 1.265 6.00 4.75 2.40 0.01 0.02 478 0.49
W1 + 1-sided GP 1 1.262 6.00 4.74 2.39 -0.01 0.03 477 0.49
W1 + 1-sided GP 2 1.265 6.00 4.74 2.40 0.02 -0.05 477 0.50
MMD, median 0 0.210 6.00 5.79 5.34 3.34 1.32 not reached
MMD, median 1 0.210 6.00 5.79 5.34 3.34 1.32 not reached
MMD, median 2 0.210 6.00 5.79 5.34 3.35 1.32 not reached
w1 = (lambda r, f: f.mean() - r.mean(), lambda r, f: -f.mean())
arms = {'logistic, sat.': (losses['logistic'][0],
lambda r, f: -softplus(f).mean(), {}),
'logistic, NS': (*losses['logistic'], {}),
'hinge': (*losses['hinge'], {}),
'W1 + GP': (*w1, dict(gp=10.0)),
'W1 + 1-sided GP': (*w1, dict(gp=10.0, one_sided=True)),
'MMD, median': (None, mmd2_median, {})}
steps, w1_runs = (0, 100, 300, 1000, 1500), [] # (arm, seed, theta, critic)
print(f'{"":17s}|grad| theta at steps {", ".join(map(str, steps))}'
' arrival farthest')
for name, (critic_loss, gen_loss, kwargs) in arms.items():
for seed in range(3):
thetas, grads, D = train_shift(critic_loss, gen_loss, seed, **kwargs)
if name.startswith('W1'):
w1_runs.append((name, seed, thetas[-1], D))
hit = np.flatnonzero(np.abs(thetas) < 0.5) # arrival: hit[0]
print(f'{name:16s}{seed}{np.median(np.abs(grads[:100])):7.3f} '
+ ''.join(f'{thetas[t]:7.2f}' for t in steps)
+ (f'{hit[0]:9d}{np.abs(thetas[hit[0]:]).max():10.2f}'
if len(hit) else ' not reached')) |grad| theta at steps 0, 100, 300, 1000, 1500 arrival farthest
logistic, sat. 0 0.006 6.00 5.99 5.96 5.85 5.76 not reached
logistic, sat. 1 0.009 6.00 5.98 5.95 5.85 5.75 not reached
logistic, sat. 2 0.013 6.00 5.98 5.96 5.85 5.77 not reached
logistic, NS 0 2.819 6.00 3.27 0.78 0.03 0.00 381 0.50
logistic, NS 1 2.724 6.00 3.42 0.81 0.02 0.00 387 0.50
logistic, NS 2 2.896 6.00 3.14 0.76 0.02 0.01 378 0.50
hinge 0 1.633 6.00 4.48 3.22 0.00 0.04 748 0.50
hinge 1 1.071 6.00 4.98 3.59 0.06 0.04 938 0.49
hinge 2 1.485 6.00 4.57 3.21 0.01 -0.02 743 0.50
W1 + GP 0 1.254 6.00 5.13 2.74 -1.13 -1.13 508 1.13
W1 + GP 1 1.256 6.00 4.96 2.59 -4.08 -7.30 494 7.47
W1 + GP 2 1.259 6.00 4.74 2.39 -1.22 -1.22 477 1.22
W1 + 1-sided GP 0 1.257 6.00 4.75 2.40 -0.06 -0.06 479 0.49
W1 + 1-sided GP 1 1.262 6.00 4.74 2.39 -0.00 0.01 476 0.50
W1 + 1-sided GP 2 1.265 6.00 4.74 2.39 -0.00 -0.02 476 0.50
MMD, median 0 0.210 6.00 5.79 5.34 3.34 1.32 not reached
MMD, median 1 0.210 6.00 5.79 5.34 3.34 1.32 not reached
MMD, median 2 0.210 6.00 5.79 5.34 3.35 1.32 not reached
실험 결과는 실전 신경망 크리틱이 비제약 이론적 최적해와 어떻게 다른지 명확히 보여 줍니다:
- 포화 대 비포화 로지스틱: 16.1절 에서처럼 포화 생성자 그레이디언트는 아주 작아서(\(\sim 0.01\)) \(\theta\) 가 \(6.0\) 에서 \(5.76\) 으로 거의 움직이지 못하는 반면, 비포화 생성자는 강한 그레이디언트(\(\sim 3\))를 받아 스텝 400 이전에 목표에 도달합니다.
- 힌지 크리틱: 이론적 최적 힌지 크리틱 \(\operatorname{sign} \lambda\) 는 두 점 구름 내부에서 기울기가 0이지만, 유한 ReLU MLP는 간격 사이를 기울기 \(1.1\text{--}1.7\) 로 매끄럽게 보간하여 스텝 \(700\text{--}950\) 무렵 생성자를 목표까지 이끌어 갑니다.
- 중앙값 대역폭 MMD: 포화 실험군을 제외하면 스텝 1,500까지 도착하지 못한 유일한 구성으로 \(\theta \approx 1.3\) 에 위치합니다. 여기서 생성자는 느리지만 멈춘 것은 아닙니다. 중앙값 휴리스틱이 대역폭을 분리 거리와 비슷한 크기로 유지해 주므로 그레이디언트가 결코 소실되지 않습니다. 다만 크기가 \(\sim 0.2\) 로 다음 항목 \(W_1\) 크리틱 기울기의 약 6분의 1 수준이어서 크기 \(0.01\) 의 단순 경사 스텝으로는 그만큼 더 오랜 시간이 걸립니다.
- 양측 대 단측 WGAN-GP: 두 \(W_1\) 실험군 모두 기울기 \(\approx 1.26\)(\(-ad + 10(a-1)^2\) 최소화로부터 \(a = 1 + d/20\))으로 생성자를 안쪽으로 당겨 스텝 500 부근에 도착합니다. 그러나 도착 이후 양측
W1 + GP실행은 예외 없이 크게 오버슈팅하는 반면(farthest\(> 1\), 최대 \(> 7\)), 단측 실행은 도착 지점보다 바깥으로 나가는 일이 전혀 없으며(farthest\(\le 0.5\)) 스텝 1,000이면 모두 원점으로부터 \(0.06\) 이내에 들어옵니다. 이유가 무엇일까요? \(\theta\) 가 \(0\) 을 가로지르는 순간 크리틱은 기울기를 음수에서 양수로 뒤집어야 합니다. 그런데 양측 페널티 \((|T'| - 1)^2\) 는 평평한 크리틱(\(T' = 0\))에 \(\gamma\) 만큼 벌점을 매기므로 기울기 0 지점에 퍼텐셜 장벽을 만들어 크리틱을 이전 기울기 부호(\(1 - d/20\))에 가두어 버리거나 모든 ReLU 유닛을 죽게 만드는데, 아래 스텝 1,500에서의 크리틱 기울기와 활성 ReLU 개수 점검이 이를 뒷받침합니다:
def slope_and_units(D, x):
"""D'(x) and, per hidden layer, the number of ReLU units active at x."""
x = h = torch.tensor([[x]], dtype=torch.float32, requires_grad=True)
active = []
for layer in D:
h = layer(h)
if isinstance(layer, nn.ReLU):
active.append(int((h > 0).sum()))
slope, = torch.autograd.grad(h.sum(), x)
return slope.item(), active
print(f"{'':19s}theta D'(theta) active D'(0) active"
' (of 32 units per layer)')
for name, seed, theta, D in w1_runs:
(s_t, a_t), (s_0, a_0) = (slope_and_units(D, x) for x in (theta, 0.0))
print(f'{name:16s}{seed}{theta:7.2f}{s_t:10.2f}{a_t[0]:5d}{a_t[1]:3d}'
f'{s_0:9.2f}{a_0[0]:5d}{a_0[1]:3d}') theta D'(theta) active D'(0) active (of 32 units per layer)
W1 + GP 0 0.30 0.00 14 0 0.00 14 0
W1 + GP 1 -7.18 1.34 11 8 1.35 12 9
W1 + GP 2 -7.61 -0.65 12 7 -0.65 12 7
W1 + 1-sided GP 0 0.02 0.41 30 3 0.41 30 3
W1 + 1-sided GP 1 0.03 0.65 25 4 0.65 25 4
W1 + 1-sided GP 2 -0.05 -0.16 30 7 -0.16 30 7
def slope_and_units(D, x):
"""D'(x) and, per hidden layer, the number of ReLU units active at x."""
def forward(x):
h, active = x, []
for layer in D.layers:
h = layer(h)
if not isinstance(layer, nnx.Linear): # an activation
active.append((h > 0).sum())
return h.sum(), active
slope, active = jax.grad(forward, has_aux=True)(jnp.array([[x]]))
return float(slope.squeeze()), [int(a) for a in active]
print(f"{'':19s}theta D'(theta) active D'(0) active"
' (of 32 units per layer)')
for name, seed, theta, D in w1_runs:
(s_t, a_t), (s_0, a_0) = (slope_and_units(D, x) for x in (theta, 0.0))
print(f'{name:16s}{seed}{theta:7.2f}{s_t:10.2f}{a_t[0]:5d}{a_t[1]:3d}'
f'{s_0:9.2f}{a_0[0]:5d}{a_0[1]:3d}') theta D'(theta) active D'(0) active (of 32 units per layer)
W1 + GP 0 -1.13 0.00 6 0 0.00 9 0
W1 + GP 1 -7.30 1.33 16 2 1.44 17 2
W1 + GP 2 -1.22 0.00 26 0 0.00 29 0
W1 + 1-sided GP 0 -0.06 0.00 32 0 0.00 32 0
W1 + 1-sided GP 1 0.01 0.56 30 4 0.56 30 4
W1 + 1-sided GP 2 -0.02 0.47 32 7 0.47 32 7
단측 페널티 \(\max(0, |T'| - 1)^2\) 는 \(|T'| \leq 1\) 일 때 아무 페널티도 부과하지 않으므로 \(\theta\) 가 데이터에 도달할 때 크리틱이 기울기 0을 자유롭게 통과하게 해 줍니다. 16.4절 에서는 평형에서 크리틱 기울기를 능동적으로 0으로 끌어당기는 영중심 페널티(\(R_1\) 과 \(R_2\))를 분석합니다.
16.2.4.3 2차원 가우스 혼합에서 다섯 가지 목적 함수 비교하기
다음으로 생성자와 데이터 지지집합이 겹칠 때 비포화 로지스틱, 최소제곱, 힌지, 제곱 힌지, 다중 대역폭 MMD(\(s \in \{0.5, 1.0, 2.0\}\))의 다섯 목적 함수를 비교합니다. 생성자 MixtureGenerator는 이동된 평균 mu_0와 더 좁은 스케일 A_0 = 0.4 * I(\(\mathrm{JS}(p, q_0) \approx 0.53\) nat)로 초기화된 3성분 가우스 혼합을 매개변수화합니다.
mu_0 = np.array([[1.0, -1.0], [-4.3, -2.0], [-1.0, 3.8]]) # off the modes
A_0 = np.stack([0.4 * np.eye(2)] * 3) # below the data's scale of 0.7
print(f'JS(p, q) at the start: {js_mixtures(mu_0, A_0):.3f} nats')JS(p, q) at the start: 0.529 nats
mu_0 = np.array([[1.0, -1.0], [-4.3, -2.0], [-1.0, 3.8]]) # off the modes
A_0 = np.stack([0.4 * np.eye(2)] * 3) # below the data's scale of 0.7
print(f'JS(p, q) at the start: {js_mixtures(mu_0, A_0):.3f} nats')JS(p, q) at the start: 0.529 nats
출발점은 데이터로부터 약 0.5 nat 떨어져 있습니다. MMD 실험군은 여러 스케일에 민감한 커널인 대역폭 \(0.5\), \(1\), \(2\) 의 세 RBF 커널 합 아래에서 불편 미니배치 \(\mathrm{MMD}^2\) 를 최소화합니다.
class MixtureGenerator(nn.Module):
"""x = mu_k + z A_k for a uniformly drawn component k."""
def __init__(self, mu, A):
super().__init__()
self.mu = nn.Parameter(to_t(mu))
self.A = nn.Parameter(to_t(A))
def forward(self, z, k):
return torch.einsum('ni,nij->nj', z, self.A[k]) + self.mu[k]
def params_np(self):
return (self.mu.detach().numpy().copy(),
self.A.detach().numpy().copy())
losses['MMD'] = (None, mmd2_loss) # no critic: MMD^2 to the real batch
class MixtureGenerator(nnx.Module):
"""x = mu_k + z A_k for a uniformly drawn component k."""
def __init__(self, mu, A):
self.mu = nnx.Param(jnp.asarray(mu, jnp.float32))
self.A = nnx.Param(jnp.asarray(A, jnp.float32))
def __call__(self, z, k):
return jnp.einsum('ni,nij->nj', z, self.A[k]) + self.mu[k]
def params_np(self):
return np.asarray(self.mu[...]), np.asarray(self.A[...])
losses['MMD'] = (None, mmd2_loss) # no critic: MMD^2 to the real batchtrain_toy는 두 손실을 인자로 받아 크리틱 스텝 한 번과 생성자 스텝 한 번을 번갈아 수행합니다. 크리틱 손실이 None으로 저장된 MMD 실험군은 크리틱 점수 대신 mmd2_loss(X, fake) 위에서 생성자 스텝만 밟습니다. 200스텝마다 정확한 \(\mathrm{JS}(p, q_t)\) 를 기록합니다.
def train_toy(critic_loss, gen_loss, seed=0, steps=6000, batch=256, lr=1e-3):
"""Fit a MixtureGenerator from (mu_0, A_0) to the data mixture, one
critic step per generator step. The losses act on the critic's scores of
the real and generated batch; with critic_loss None, gen_loss acts on the
two batches. Returns the exact JS(p, q_t) every 200 steps."""
rng = np.random.default_rng(seed)
torch.manual_seed(seed)
G, D = MixtureGenerator(mu_0, A_0), make_critic()
opt_G = torch.optim.Adam(G.parameters(), lr)
opt_D = torch.optim.Adam(D.parameters(), 2 * lr)
trace = []
for t in range(steps):
X = to_t(sample_mixture(batch, mu_p, A_p, rng))
z = to_t(rng.standard_normal((batch, 2)))
k = torch.tensor(rng.integers(0, 3, batch))
if critic_loss is not None:
opt_D.zero_grad()
critic_loss(D(X), D(G(z, k).detach())).backward()
opt_D.step()
opt_G.zero_grad()
fake = G(z, k)
loss = (gen_loss(X, fake) if critic_loss is None
else gen_loss(D(X), D(fake)))
loss.backward()
opt_G.step()
if t % 200 == 0:
trace.append(js_mixtures(*G.params_np()))
return np.array(trace)
@nnx.jit(static_argnums=(0, 1))
def train_toy_step(critic_loss, gen_loss, G, D, opt_G, opt_D, X, z, k):
"""A critic step (unless critic_loss is None), then a generator step."""
if critic_loss is not None: # the generator is fixed here
fake = G(z, k)
opt_D.update(D, nnx.grad(lambda D_: critic_loss(D_(X), D_(fake)))(D))
def g_loss(G_):
fake = G_(z, k)
return (gen_loss(X, fake) if critic_loss is None
else gen_loss(D(X), D(fake)))
opt_G.update(G, nnx.grad(g_loss)(G))
def train_toy(critic_loss, gen_loss, seed=0, steps=6000, batch=256, lr=1e-3):
"""Fit a MixtureGenerator from (mu_0, A_0) to the data mixture, one
critic step per generator step. The losses act on the critic's scores of
the real and generated batch; with critic_loss None, gen_loss acts on the
two batches. Returns the exact JS(p, q_t) every 200 steps."""
rng = np.random.default_rng(seed)
G, D = MixtureGenerator(mu_0, A_0), make_critic(nnx.Rngs(seed))
opt_G = nnx.Optimizer(G, optax.adam(lr), wrt=nnx.Param)
opt_D = nnx.Optimizer(D, optax.adam(2 * lr), wrt=nnx.Param)
trace = []
for t in range(steps):
X = jnp.asarray(sample_mixture(batch, mu_p, A_p, rng), jnp.float32)
z = jnp.asarray(rng.standard_normal((batch, 2)), jnp.float32)
k = jnp.asarray(rng.integers(0, 3, batch))
train_toy_step(critic_loss, gen_loss, G, D, opt_G, opt_D, X, z, k)
if t % 200 == 0:
trace.append(js_mixtures(*G.params_np()))
return np.array(trace)목적 함수당 세 시드 각각에 대해 마지막 2,000스텝 동안의 \(\mathrm{JS}(p, q_t)\) 중앙값과 \(\mathrm{JS}(p, q_t) < 0.1\) 및 \(< 0.01\) nat에 처음 도달하는 스텝을 보고합니다.
def first_below(trace, level):
"""First recorded step (one record per 200 steps) with JS below level."""
hits = np.flatnonzero(trace < level)
return f'{200 * hits[0]:6d}' if len(hits) else ' n/a'
runs = {name: [train_toy(*pair, seed=seed) for seed in range(3)]
for name, pair in losses.items()}
print(f'{"three runs:":14s}{"median JS, last 2,000 steps":>27s}'
f'{"first JS < 0.1":>21s}{"first JS < 0.01":>21s}')
for name, traces in runs.items():
medians = [np.median(trace[-2000 // 200:]) for trace in traces]
print(f'{name:14s} ' + ''.join(f'{m:8.4f}' for m in medians)
+ ' ' + ''.join(first_below(trace, 0.1) for trace in traces)
+ ' ' + ''.join(first_below(trace, 0.01) for trace in traces))
d2l.plot(np.arange(len(runs['logistic'][0])) * 200,
[traces[0] for traces in runs.values()], xlabel='step',
ylabel='JS(p, q_t)', yscale='log', legend=list(runs), figsize=(5, 3))three runs: median JS, last 2,000 steps first JS < 0.1 first JS < 0.01
logistic 0.0008 0.0008 0.0008 2000 2000 2200 2400 2400 2400
least squares 0.0009 0.0009 0.0008 2000 2200 1800 2200 2400 2200
hinge 0.0070 0.0071 0.0033 1800 1800 1400 2000 2000 2400
squared hinge 0.0013 0.0008 0.0024 1400 1400 1400 2200 2200 2200
MMD 0.0001 0.0001 0.0001 1200 1200 1200 2600 2600 2600
def first_below(trace, level):
"""First recorded step (one record per 200 steps) with JS below level."""
hits = np.flatnonzero(trace < level)
return f'{200 * hits[0]:6d}' if len(hits) else ' n/a'
runs = {name: [train_toy(*pair, seed=seed) for seed in range(3)]
for name, pair in losses.items()}
print(f'{"three runs:":14s}{"median JS, last 2,000 steps":>27s}'
f'{"first JS < 0.1":>21s}{"first JS < 0.01":>21s}')
for name, traces in runs.items():
medians = [np.median(trace[-2000 // 200:]) for trace in traces]
print(f'{name:14s} ' + ''.join(f'{m:8.4f}' for m in medians)
+ ' ' + ''.join(first_below(trace, 0.1) for trace in traces)
+ ' ' + ''.join(first_below(trace, 0.01) for trace in traces))
d2l.plot(np.arange(len(runs['logistic'][0])) * 200,
[traces[0] for traces in runs.values()], xlabel='step',
ylabel='JS(p, q_t)', yscale='log', legend=list(runs), figsize=(5, 3))three runs: median JS, last 2,000 steps first JS < 0.1 first JS < 0.01
logistic 0.0011 0.0008 0.0019 2200 2200 1800 2400 2400 2400
least squares 0.0010 0.0007 0.0006 2200 2000 1800 2400 2200 2000
hinge 0.0069 0.0036 0.0064 1400 1400 1800 2000 2200 2000
squared hinge 0.0012 0.0007 0.0009 1400 1400 1200 2000 2000 2400
MMD 0.0001 0.0001 0.0001 1200 1200 1200 2600 2600 2600
다섯 목적 함수 모두 \(\mathrm{JS}(p, q_t)\) 를 \(0.53\) nat에서 천분의 몇 nat 이하로 줄입니다. 움직이는 크리틱을 추적하지 않는 직접 MMD 최소화가 가장 촘촘한 최종 적합(\(0.0001\) nat)을 달성하는 반면, 힌지 손실은 매끄러운 연결 함수를 가진 목적 함수들(로지스틱, 최소제곱, 제곱 힌지 모두 \(\leq 0.0024\) nat)보다 약간 높은 수준(\(0.003\text{--}0.007\) nat)에 안착합니다(3 참조). 다음으로 16.3절 에서는 각 샘플을 고립시켜 채점하는 대신 실제 샘플과 생성 샘플을 쌍으로 묶어 비교하는 크리틱들을 살펴봅니다.
16.2.5 요약
모든 단일 샘플 적대적 목적 함수는 크리틱 함수족 \(\mathcal{T}\) 위에서 기대 보수들의 상한을 취하므로(식 16.2.1), 생성자 매개변수 \(\theta\) 에 대해서는 비볼록일지라도 분포 \(q\) 에 대해서는 항상 볼록합니다. 비제약 크리틱에서는 대칭 마진 분류 손실들이 베이즈 위험 격차 \(\Delta_\ell(p, q)\) 가 정하는 \(f\)-발산을 평가하며(표 16.2.2) 최적 크리틱이 \(\lambda = \log(p/q)\) 의 단조 연결 함수를 출력하는 한편, Fenchel–Young 변분 하한(식 16.2.5)은 이 쌍대성을 비대칭 \(f\)-발산으로 확장합니다. 비선형 보수를 제약된 함수족 \(\mathcal{F}\) 위의 선형 기댓값으로 바꾸면 RKHS 단위 공 위의 최대 평균 불일치와 1-립시츠 함수 위의 Wasserstein-1을 비롯한 적분 확률 거리가 정의됩니다. 지지집합이 분리될 때 \(f\)-발산은 포화되는 반면 \(W_1\) 은 단위 기울기를 유지하고 \(\mathrm{MMD}^2\) 는 커널 대역폭까지 유의미한 그레이디언트를 제공하며, 실전에서는 유한 신경망 크리틱이 비포화 생성자 손실과 짝지어질 때마다 간격 너머를 매끄럽게 보간합니다.
16.2.6 연습 문제
[code] 분포 공간 대 매개변수 공간에서의 볼록성. 식 16.2.1 형태를 가진 모든 목적 함수는 \(q\) 에 대해 볼록하지만 모수적 생성자는 \(q\) 를 직접 바꾸는 대신 \(\theta\) 를 바꿉니다.
normal_pdf,js_1d,xs를 사용하십시오.- \(p = \mathcal{N}(0, 1)\), \(q_0 = \mathcal{N}(8, 1)\) 이라 합시다. 선형 혼합 경로 \(q_t = (1 - t)\, q_0 + t\, p\) 를 따라 2차 차분으로 \(\mathrm{JS}(p, q_t)\) 가 \(t \in [0, 1]\) 에 대해 볼록함을 확인하십시오.
- 이제 \(p = 0.7\, \mathcal{N}(-4, 1) + 0.3\, \mathcal{N}(4, 1)\) 이고 \(q_\theta = \mathcal{N}(\theta, 1)\) 이라 합시다. \(\theta \in [-6, 6]\) 에 대해 \(\mathrm{JS}(p, q_\theta)\) 를 그리고 국소 최솟값과 극댓값을 찾으십시오.
- \(\theta\) 에 대한 이러한 비볼록 지형이 왜 \(q\) 에 대한 볼록성과 모순되지 않습니까?
젠센–섀넌 볼록 켤레 함수. 젠센–섀넌 발산의 두 배는 발산 함수 \(f(u) = u \log u - (u + 1) \log \frac{u + 1}{2}\) 에 대응합니다.
[code] 가우스 혼합에서의 생성자 가중치와 크리틱 지연. ●
train_toy와 16.2.4.3절 의 다섯 목적 함수를 사용하십시오.- 로지스틱 크리틱 손실을 선형 생성자 손실 \(-D(x')\)(가중치 \(w = 1\))과 짝짓고 세 시드에 걸쳐 \(\mathrm{JS}(p, q_t) < 0.1\) nat에 처음 도달하는 스텝 기준으로 비포화 손실 \(-\log \sigma(D(x'))\) 과 비교하십시오. 샘플별 가중치로 그 차이를 설명하십시오.
- 세 시드에 걸쳐 두 가지 통제 실험, 즉 (i) 생성자 업데이트당 5회 크리틱 업데이트, (ii) \(4\times\) 더 큰 크리틱 배치 크기를 실행하여 힌지 손실의 약간 더 높은 최종 \(\mathrm{JS}\) 가 크리틱 지연 때문인지 미니배치 잡음 때문인지 검정하십시오.
[code] 표본 복잡도와 차원. ● \(\|\boldsymbol{\mu}\| = 1\) 인 \(p = \mathcal{N}(\mathbf{0}, \mathbf{I}_{d_x})\) 와 \(q = \mathcal{N}(\boldsymbol{\mu}, \mathbf{I}_{d_x})\) 를 두어 모든 차원 \(d_x\) 에서 \(W_1(p, q) = 1\) 이 되게 합시다.
- \(d_x \in \{1, 2, 10, 50\}\) 및 \(n \in \{100, 400, 1600\}\) 에 대해 최적 선형 할당(
scipy.optimize.linear_sum_assignment)으로 크기 \(n\) 의 두 표본으로부터 \(W_1\) 을 추정하고 로그–로그 축 위에 \(n\) 에 따른 상대 오차를 그리십시오. 대역폭 \(s = \sqrt{d_x}\) 인 RBF 커널을 쓴 불편 \(\mathrm{MMD}^2\) 추정량과 비교하십시오. - 차원 \(d_x = 50\) 에서 같은 분포 \(p\) 로부터 뽑은 크기 \(n = 256\) 의 독립 표본 두 개 사이의 경험적 \(W_1\) 거리를 측정하십시오.
grid_2d위의 구적법으로critics['forward KL']에 대한 식 16.2.5 의 순방향 KL 변분 하한을 평가하고 참값 \(D_{\textrm{KL}}(p \,\|\, q) \approx 0.16\) nat 및 크기 512의 미니배치 추정치들과 비교하십시오. \(q(x')\) 가 작은 영역에서 \(T(x')\) 가 \(1 + \lambda(x')\) 를 넘어설 때 \(q\) 에서 뽑은 유한 미니배치가 왜 하한을 과대추정할 수 있습니까?
- \(d_x \in \{1, 2, 10, 50\}\) 및 \(n \in \{100, 400, 1600\}\) 에 대해 최적 선형 할당(
분류 손실로부터 유도되는 대칭 \(f\)-발산. ●● 식 16.2.2 의 모든 마진 분류 손실은 대칭 베이즈 위험 \(L(\eta) = L(1 - \eta)\) 를 가지므로 대칭 \(f\)-발산을 평가합니다. 역으로(Nguyen 기타 (2009년), 따름정리 3), \(f\) 가 \(f(1) = 0\), \(f(u) = u f(1/u)\), \(f(0) = \lim_{u \to 0} f(u) < \infty\) 를 만족하는 \((0, \infty)\) 위의 볼록 함수라 하고 다음과 같이 정의합시다:
\[ L(\eta) = 2 f(0) - 2 (1 - \eta)\, f\!\left( \frac{\eta}{1 - \eta} \right), \qquad 0 < \eta < 1. \]
- \(L(\eta)\) 가 오목 함수이고 \(\tfrac12\) 에 대해 대칭이며 \(\eta \to 0\) 또는 \(1\) 일 때 0으로 사라지고 베이즈 위험 격차 \(\Delta_\ell(p, q) = D_f(p \,\|\, q)\) 를 가짐을 보이십시오.
- 미분 가능한 \(L\) 과 \(\hat\eta = \sigma(t)\) 에 대해 실제 샘플 손실을 \(-\ell(t) = L(\hat\eta) + (1 - \hat\eta) L'(\hat\eta)\) 로 정의하십시오. \(-\ell(-t) = L(\hat\eta) - \hat\eta L'(\hat\eta)\) 이고 조건부 위험이 \(\hat\eta = \eta\) 에서 최솟값 \(L(\eta)\) 를 가지며 \(-\ell(t) \geq 0\) 임을 보이십시오.
- 젠센–섀넌 발산에 이 구성을 적용하면 로지스틱 손실이 복원됨을 확인하십시오.