16.4  그레이디언트 페널티와 수렴

16.1절 의 Fashion-MNIST 실험에서 판별자 손실도 생성자 손실도 이론적 평형값에 안착하지 않았습니다. 교대 경사 하강법이 단지 느리게 수렴하는 것일까요, 아니면 평형에 도달하지 못한 채 끝없이 평형 주위를 맴돌 수도 있을까요? 16.1절 부터 16.3절 까지의 모집단 발산 분석들은 크리틱이 정확한 최적해 \(D^\star\) 에 놓여 있을 때의 미니맥스 목적 함수를 규명하지만, 실전에서는 두 신경망이 작은 동시 또는 교대 그레이디언트 스텝을 밟으며 매 업데이트가 상대 신경망의 목적 함수를 움직여 놓습니다.

경사 기반 훈련의 동역학을 직접 분석하기 위해 Mescheder 기타 (2018년) 의 연구는 점질량 데이터 분포, 점질량 생성자, 선형 크리틱으로 이루어진 최소 2매개변수 문제인 Dirac-GAN을 도입했습니다. 이 2매개변수 시스템에서조차 비정칙화 경사 하강법은 수렴에 실패하는 반면, 크리틱 입력 그레이디언트의 제곱 노름에 페널티(\(R_1\) 과 \(R_2\))를 매기면 평형이 국소 점근 안정해집니다. 이 영중심 그레이디언트 페널티들을 16.3절 의 상대론적 페어링 목적 함수와 결합하면 이 장의 나머지 부분 전반에서 사용하는 R3GAN 레시피 (Huang 기타 2024년) 가 탄생합니다.

16.4.1 Dirac-GAN

16.4.1.1 2매개변수 미니맥스 시스템

데이터 분포를 원점의 점질량 \(p = \delta_0\) 이라 하고 생성자가 \(\theta \in \mathbb{R}\) 에 점질량 \(q_\theta = \delta_\theta\) 를 놓으며(\(\theta = 0\) 일 때 그리고 그때만 \(q_\theta = p\)) 크리틱이 편향 없는 선형 함수 \(D_\psi(x) = \psi x\) 라 합시다. 대칭 마진 목적 함수 \(V_\ell(D) = \mathbb{E}_{x \sim p}[\ell(D(x))] + \mathbb{E}_{x' \sim q}[\ell(-D(x'))]\) (16.2절) 아래에서 두 기댓값은 단일 평가로 축약됩니다:

\[ \begin{aligned} V(\theta, \psi) &= \ell\big(D_\psi(0)\big) + \ell\big({-D_\psi(\theta)}\big) \\ &= \ell(0) + \ell(-\psi\theta). \end{aligned} \tag{16.4.1}\]

여기서는 \(\ell'(0) = \tfrac12\), \(\ell''(0) = -\tfrac14\) 이면서 \(\ell'(t) = \sigma(-t) > 0\), \(\ell''(t) = -\sigma(t)\sigma(-t) < 0\) 을 만족하는 로지스틱 보수 \(\ell(t) = \log \sigma(t)\) 를 택합니다.

임의의 \(\theta \neq 0\) 에 대해 \(p\) 와 \(q_\theta\) 의 지지집합은 서로소입니다. \(\psi\) 에 대해 \(V(\theta, \psi)\) 를 최대화하면 \(\psi\theta \to -\infty\) 로 보내져 모든 \(\theta \neq 0\) 에 대해 상수 \(\sup_\psi V(\theta, \psi) = \ell(0)\) 을 내놓으며 이는 \(\theta\) 에 대해 0의 그레이디언트를 줍니다.

16.4.1.2 연속 시간에서의 비감쇠 진동

\(\sup_\psi V(\theta, \psi)\) 를 한 번에 푸는 대신 그레이디언트 훈련은 현재 값에서 \(\theta\) 와 \(\psi\) 를 점진적으로 갱신합니다. 식 16.4.1 의 유일한 정류점은 평형 \((\theta, \psi) = (0, 0)\) 입니다. 동시 연속 시간 그레이디언트 흐름(\(\dot\theta = -\partial_\theta V\), \(\dot\psi = +\partial_\psi V\)) 아래에서는 다음과 같습니다:

\[ \begin{aligned} \dot\theta &= -\partial_\theta V = \psi\, \ell'(-\psi\theta), \\ \dot\psi &= +\partial_\psi V = -\theta\, \ell'(-\psi\theta). \end{aligned} \tag{16.4.2}\]

속도 벡터 \(\mathbf{u}(\theta, \psi) = \ell'(-\psi\theta)\,(\psi, -\theta)\) 가 모든 곳에서 상태 벡터 \((\theta, \psi)\) 와 직교하므로 원점까지의 제곱 거리가 보존됩니다:

\[ \begin{aligned} \frac{d}{dt}\big(\theta^2 + \psi^2\big) &= 2\theta\psi\,\ell'(-\psi\theta) - 2\psi\theta\,\ell'(-\psi\theta) = 0 . \end{aligned} \]

임의의 순증가 보수 \(\ell\) 에 대해 모든 궤적은 \((0, 0)\) 주위를 일정한 반지름으로 도는 닫힌 원입니다. 즉 생성자 매개변수 \(\theta\) 는 끝내 수렴하지 않은 채 \(0\) 을 가로질러 앞뒤로 진동합니다.

\((\theta, \psi) = (0, 0)\) 주위에서 식 16.4.2 의 동역학을 선형화하면(26.1.2.5절) 야코비 행렬과 고윳값을 얻습니다:

\[ J = \begin{pmatrix} 0 & \ell'(0) \\ -\ell'(0) & 0 \end{pmatrix}, \qquad \nu_{1,2} = \pm\, i\, \ell'(0). \tag{16.4.3}\]

순허수 고윳값들은 선형 중심점(center, 쌍선형 안장 문제 \(\min_\theta \max_\psi \theta\psi\), Daskalakis 기타 (2018년))에 해당합니다. 스칼라 인수 \(\ell'(-\psi\theta) = \sigma(D_\psi(\theta)) = w_{\textrm{sat}}\) 는 두 성분에 동시에 곱해지므로 원을 따라 도는 각속도의 스케일만 바꿀 뿐이라는 점에 주목합시다.

16.4.1.3 이산 시간에서의 외향 나선과 극한 주기 궤도

이산 시간에서 스텝 크기 \(h > 0\) 인 동시 경사 하강법은 \((\theta, \psi) \mapsto (\theta, \psi) + h\,\mathbf{u}(\theta, \psi)\) 로 갱신합니다. \(\mathbf{u}(\theta, \psi) \perp (\theta, \psi)\) 이므로 피타고라스 정리에 의해 다음을 얻습니다:

\[ \begin{aligned} \big\| (\theta, \psi) + h\, \mathbf{u} \big\|^2 &= \big\| (\theta, \psi) \big\|^2 + h^2 \big\| \mathbf{u} \big\|^2 . \end{aligned} \]

따라서 임의의 \(h > 0\) 에 대해 모든 동시 이산 스텝은 평형으로부터의 거리를 순증가시켜 반복점들이 바깥으로 나선을 그리며 퍼져 나가게 만듭니다(1 참조).

교대 그레이디언트 업데이트(\(\psi\) 를 먼저 갱신한 뒤 갱신된 \(\psi\) 를 써서 \(\theta\) 갱신)는 조금 더 낫습니다. \((0, 0)\) 근처에서 각 반스텝은 넓이를 보존하는 선형 전단 변환(shear)이어서 합성 야코비 행렬의 행렬식이 \(1\) 입니다. \(h\,\ell'(0) \leq 2\) 이면 두 고윳값이 모두 단위 원 위에 놓이므로 (Mescheder 기타 2018년) 교대 반복점들은 수렴하지 않은 채 원점 주위의 유계 띠 안에서 궤도를 돕니다(4 참조). 원점에서 동일한 선형화 \(J\) 를 공유하는 비포화 생성자 손실도, 똑같은 그레이디언트 장을 갖는 상대론적 페어링 손실(\(\ell(D_\psi(0) - D_\psi(\theta)) = \ell(-\psi\theta)\))도 이 국소 고윳값들을 바꾸지 못합니다.

16.4.2 영중심 그레이디언트 페널티

평형 \((\theta, \psi) = (0, 0)\) 을 국소 점근 안정하게 만들려면 야코비 행렬의 고윳값들을 허수축에서 열린 왼쪽 반평면 \(\operatorname{Re}(\nu) < 0\) 으로 옮겨야 합니다. 평형 크리틱은 평평해야 하므로(\(q = p\) 일 때 \(\nabla_x D^\star(x) = 0\)), 크리틱 입력 그레이디언트의 제곱 노름에 페널티를 매기면 평형 \(q = p\) 를 이동시키지 않으면서 크리틱에 감쇠를 더해 줍니다.

Mescheder 기타 (2018년) 의 연구는 실제 데이터 \(x \sim p\) 에서 평가하는 \(R_1\) 과 생성 샘플 \(x' \sim q\) 에서 평가하는 \(R_2\) 의 두 영중심 그레이디언트 페널티(zero-centered gradient penalties)를 정의합니다:

\[ \begin{aligned} R_1 &= \frac{\gamma}{2}\, \mathbb{E}_{x \sim p}\Big[ \big\| \nabla_x D(x) \big\|^2 \Big], \\ R_2 &= \frac{\gamma}{2}\, \mathbb{E}_{x' \sim q}\Big[ \big\| \nabla_{x'} D(x') \big\|^2 \Big], \end{aligned} \tag{16.4.4}\]

여기서 페널티 가중치는 \(\gamma > 0\) 입니다. 크리틱은 \(V_\ell(D) - R_1 - R_2\) 를 최대화하며 생성자 목적 함수는 바뀌지 않습니다. \(m = (p + q)/2\) 라 쓰면 두 페널티의 합은 혼합 분포 아래 기대 제곱 그레이디언트 노름이 됩니다:

\[ \begin{aligned} R_1 + R_2 &= \gamma\, \mathbb{E}_{x \sim m}\Big[ \big\| \nabla_x D(x) \big\|^2 \Big], \qquad m = \frac{p + q}{2}. \end{aligned} \tag{16.4.5}\]

16.4.2.1 Dirac-GAN 감쇠시키기

선형 크리틱 \(D_\psi(x) = \psi x\) 에서는 모든 곳에서 \(\nabla_x D_\psi(x) = \psi\) 이므로 \(R_1 = R_2 = \tfrac{\gamma}{2}\psi^2\) 입니다. 크리틱 목적 함수에서 \(\tfrac{\gamma}{2}\psi^2\) 을 빼면 \(\dot\psi\) 에 선형 감쇠항 \(-\gamma\psi\) 가 더해집니다(\(R_1\) 과 \(R_2\) 를 둘 다 포함하면 \(-2\gamma\psi\)):

\[ \dot\theta = \psi\,\ell'(-\psi\theta), \qquad \dot\psi = -\theta\,\ell'(-\psi\theta) - \gamma\psi . \]

\((0, 0)\) 에서의 야코비 행렬과 고윳값은 다음과 같이 바뀝니다:

\[ J_\gamma = \begin{pmatrix} 0 & \ell'(0) \\ -\ell'(0) & -\gamma \end{pmatrix}, \qquad \nu_{1,2} \;=\; -\frac{\gamma}{2} \pm \sqrt{ \frac{\gamma^2}{4} - \ell'(0)^2 } . \tag{16.4.6}\]

모든 \(\gamma > 0\) 에 대해 두 고윳값 모두 순음의 실수부(\(\operatorname{Re}(\nu_{1,2}) < 0\))를 가지므로 평형 \((0, 0)\) 은 국소 지수 안정해집니다. 특성다항식 \(\nu^2 + \gamma\nu + \ell'(0)^2 = 0\) 은 세 가지 체제를 갖는 감쇠 조화 진동자(26.1.2.5절)의 특성다항식과 정확히 일치합니다:

  1. 부족감쇠(\(\gamma < 2\ell'(0)\)): 실수부가 \(-\gamma/2\) 인 켤레 복소 고윳값을 가지며 궤적이 안쪽으로 나선을 그리며 들어옵니다(\(h < \gamma / \ell'(0)^2\) 일 때 동시 오일러 스텝 아래 수렴, 1 참조).
  2. 임계감쇠(\(\gamma = 2\ell'(0)\), 즉 로지스틱 손실에서 \(\gamma = 1\)): 중근인 실수 고윳값 \(\nu = -\ell'(0)\) 을 가져 진동 없이 가장 빠르게 감쇠합니다.
  3. 과감쇠(\(\gamma > 2\ell'(0)\)): 두 개의 음의 실수 고윳값을 가지며 \(\gamma\) 가 커질수록 느린 모드 \(\nu \approx -\ell'(0)^2/\gamma\) 가 더 천천히 감쇠합니다.

16.4.2.2 위상 평면도

4차 룽게–쿠타(rk4_step), 동시 전방 오일러(euler_step), 교대 그레이디언트 업데이트(alt_step)를 사용해 \((\theta_0, \psi_0) = (1, 1)\)(초기 반지름 \(\sqrt{2} \approx 1.41\))에서 식 16.4.2 의 미분방정식을 적분하여 이 네 가지 체제를 검증합니다.

def dirac_field(theta, psi, gamma=0.0):
    """Simultaneous gradient field of the Dirac-GAN with the logistic loss."""
    w = 1.0 / (1.0 + np.exp(-psi * theta))      # l'(-psi theta) = w_sat
    return np.array([psi * w, -theta * w - gamma * psi])

def euler_step(x, h, gamma):                     # one simultaneous step
    return x + h * dirac_field(*x, gamma)

def alt_step(x, h, gamma):                       # critic first, then generator
    theta, psi = x
    psi = psi + h * dirac_field(theta, psi, gamma)[1]
    return np.array([theta + h * dirac_field(theta, psi, gamma)[0], psi])

def rk4_step(x, h, gamma):                       # one RK4 step of the ODE
    k1 = dirac_field(*x, gamma)
    k2 = dirac_field(*(x + h / 2 * k1), gamma)
    k3 = dirac_field(*(x + h / 2 * k2), gamma)
    k4 = dirac_field(*(x + h * k3), gamma)
    return x + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)

def trajectory(step, x0, h, steps, gamma=0.0):
    xs = [np.array(x0)]
    for _ in range(steps):
        xs.append(step(xs[-1], h, gamma))
    return np.stack(xs)
def dirac_field(theta, psi, gamma=0.0):
    """Simultaneous gradient field of the Dirac-GAN with the logistic loss."""
    w = 1.0 / (1.0 + np.exp(-psi * theta))      # l'(-psi theta) = w_sat
    return np.array([psi * w, -theta * w - gamma * psi])

def euler_step(x, h, gamma):                     # one simultaneous step
    return x + h * dirac_field(*x, gamma)

def alt_step(x, h, gamma):                       # critic first, then generator
    theta, psi = x
    psi = psi + h * dirac_field(theta, psi, gamma)[1]
    return np.array([theta + h * dirac_field(theta, psi, gamma)[0], psi])

def rk4_step(x, h, gamma):                       # one RK4 step of the ODE
    k1 = dirac_field(*x, gamma)
    k2 = dirac_field(*(x + h / 2 * k1), gamma)
    k3 = dirac_field(*(x + h / 2 * k2), gamma)
    k4 = dirac_field(*(x + h * k3), gamma)
    return x + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)

def trajectory(step, x0, h, steps, gamma=0.0):
    xs = [np.array(x0)]
    for _ in range(steps):
        xs.append(step(xs[-1], h, gamma))
    return np.stack(xs)

모든 경로는 검은 십자 표시된 평형으로부터 거리 \(\sqrt 2 \approx 1.41\) 떨어진 빨간 점 \((\theta, \psi) = (1, 1)\) 에서 출발합니다. 왼쪽 패널은 연속 흐름을 보여 줍니다. 가운데 패널은 크기 \(h = 0.2\) 의 동시 스텝 300번과 교대 스텝 2,000번을 보여 줍니다. 오른쪽 패널은 부족감쇠 체제의 \(\gamma = 0.3\) 과 임곗값 \(\gamma = 1\) 에서 페널티를 넣은 같은 크기의 동시 스텝 300번을 보여 줍니다.

x0 = np.array([1.0, 1.0])
panels = {'flow': {'RK4': trajectory(rk4_step, x0, 0.05, 800)},
          'steps': {'simultaneous': trajectory(euler_step, x0, 0.2, 300),
                    'alternating': trajectory(alt_step, x0, 0.2, 2000)},
          'penalized': {
              'gamma = 0.3': trajectory(euler_step, x0, 0.2, 300, gamma=0.3),
              'gamma = 1': trajectory(euler_step, x0, 0.2, 300, gamma=1.0)}}
fig, axes = d2l.plt.subplots(1, 3, figsize=(9.5, 3.4))
for ax, (title, paths) in zip(axes, panels.items()):
    for name, P in paths.items():
        r = np.linalg.norm(P, axis=1)            # distance to the equilibrium
        late = r[len(r) // 2:]
        print(f'{title}, {name}: {r[0]:.3g} -> {r[-1]:.3g} in {len(r) - 1} '
              f'steps; second half in [{late.min():.3g}, {late.max():.3g}]')
    lim = 1.25 * max(np.abs(P).max() for P in paths.values())
    d2l.plot([P[:, 0] for P in paths.values()] + [x0[:1], [0.0]],
             [P[:, 1] for P in paths.values()] + [x0[1:], [0.0]],
             r'$\theta$', r'$\psi$', list(paths) if len(paths) > 1 else None,
             xlim=(-lim, lim), ylim=(-lim, lim), axes=ax,
             fmts=('C0-', 'C1-')[:len(paths)] + ('C3o', 'k+'),
             legend_loc='lower right' if title == 'penalized' else None)
    ax.set_title(title)
    ax.set_aspect('equal')
fig.tight_layout()
flow, RK4: 1.41 -> 1.41 in 800 steps; second half in [1.41, 1.41]
steps, simultaneous: 1.41 -> 2.87 in 300 steps; second half in [2.44, 2.87]
steps, alternating: 1.41 -> 1.36 in 2000 steps; second half in [1.34, 1.42]
penalized, gamma = 0.3: 1.41 -> 0.000652 in 300 steps; second half in [0.000652, 0.0396]
penalized, gamma = 1: 1.41 -> 6.97e-12 in 300 steps; second half in [6.97e-12, 2.33e-05]

x0 = np.array([1.0, 1.0])
panels = {'flow': {'RK4': trajectory(rk4_step, x0, 0.05, 800)},
          'steps': {'simultaneous': trajectory(euler_step, x0, 0.2, 300),
                    'alternating': trajectory(alt_step, x0, 0.2, 2000)},
          'penalized': {
              'gamma = 0.3': trajectory(euler_step, x0, 0.2, 300, gamma=0.3),
              'gamma = 1': trajectory(euler_step, x0, 0.2, 300, gamma=1.0)}}
fig, axes = d2l.plt.subplots(1, 3, figsize=(9.5, 3.4))
for ax, (title, paths) in zip(axes, panels.items()):
    for name, P in paths.items():
        r = np.linalg.norm(P, axis=1)            # distance to the equilibrium
        late = r[len(r) // 2:]
        print(f'{title}, {name}: {r[0]:.3g} -> {r[-1]:.3g} in {len(r) - 1} '
              f'steps; second half in [{late.min():.3g}, {late.max():.3g}]')
    lim = 1.25 * max(np.abs(P).max() for P in paths.values())
    d2l.plot([P[:, 0] for P in paths.values()] + [x0[:1], [0.0]],
             [P[:, 1] for P in paths.values()] + [x0[1:], [0.0]],
             r'$\theta$', r'$\psi$', list(paths) if len(paths) > 1 else None,
             xlim=(-lim, lim), ylim=(-lim, lim), axes=ax,
             fmts=('C0-', 'C1-')[:len(paths)] + ('C3o', 'k+'),
             legend_loc='lower right' if title == 'penalized' else None)
    ax.set_title(title)
    ax.set_aspect('equal')
fig.tight_layout()
flow, RK4: 1.41 -> 1.41 in 800 steps; second half in [1.41, 1.41]
steps, simultaneous: 1.41 -> 2.87 in 300 steps; second half in [2.44, 2.87]
steps, alternating: 1.41 -> 1.36 in 2000 steps; second half in [1.34, 1.42]
penalized, gamma = 0.3: 1.41 -> 0.000652 in 300 steps; second half in [0.000652, 0.0396]
penalized, gamma = 1: 1.41 -> 6.97e-12 in 300 steps; second half in [6.97e-12, 2.33e-05]

위상 평면도는 네 가지 예측을 모두 확인해 줍니다. 연속 흐름(RK4)은 반지름 \(1.41\) 원 위를 돌고, 동시 오일러 스텝은 300스텝 뒤 반지름 \(2.87\) 로 바깥 나선을 그리며, 교대 스텝은 \([1.34, 1.42]\) 안에서 궤도를 도는 반면, 영중심 페널티를 추가하면 동시 오일러 스텝이 원점으로 곧장 수렴합니다(부족감쇠 \(\gamma = 0.3\) 에서 \(6.5 \times 10^{-4}\), 임계감쇠 \(\gamma = 1\) 에서 \(7 \times 10^{-12}\)).

16.4.2.3 일반 신경망의 국소 수렴과 페널티 비교

Mescheder 기타 (2018년) 의 연구는 이 국소 안정성 분석을 2매개변수 Dirac-GAN에서 일반 신경망으로 확장했습니다. 생성자가 데이터 분포 \(p\) 를 표현하고 \(\operatorname{supp}(p)\) 위에서 크리틱이 평평한 평형 근처에서, 크리틱이 1차 생성자 교란을 감지할 만큼 충분한 국소 용량을 갖추고 있기만 하면 \(R_1\) 또는 \(R_2\)(및 \(\ell'(0) \neq 0, \ell''(0) < 0\) 을 만족하는 강오목 손실)를 결합한 동시·교대 그레이디언트 업데이트는 평형 다양체로 지수 수렴합니다(Huang 기타 (2024년) 의 연구는 상대론적 페어링 목적 함수에 대해 유사한 국소 정리를 확립했습니다).

이 분석은 두 가지 실전 설계 선택도 명쾌하게 설명해 줍니다:

  • 영중심(\(R_1, R_2\)) 대 1중심(WGAN-GP) 페널티: WGAN-GP는 \((\|\nabla_x D\| - 1)^2\) 에 벌점을 매겨 \(q = p\) 일 때조차 크리틱이 단위 기울기를 유지하도록 강제합니다. 선형 보수 \(\ell(t) = t\) 를 쓴 Dirac-GAN에서 1중심 페널티는 \(\theta = 0\) 으로의 수렴을 가로막습니다. \(\gamma \geq 2\) 이면 Wasserstein 그레이디언트가 페널티와 균형을 이루는 \(|\theta| = \gamma\) 에 생성자를 세워 버리고, 더 작은 \(\gamma\) 에서는 생성자가 이 지점을 지나쳐 계속 순환합니다(6 참조).
  • \(R_1\) 과 \(R_2\) 동시 사용 대 \(R_1\) 단독 사용: \(q = p\) 근처에서는 \(R_1\) 과 \(R_2\) 가 동등합니다. 그러나 평형에서 멀리 떨어져 있을 때 \(R_1\) 은 실제 데이터 점 \(x \sim p\) 에서만 크리틱 기울기에 페널티를 매기므로 생성 점 \(x' \sim q\) 에서의 기울기는 제약되지 않은 채 남습니다(예컨대 \(D_c(x) = -cx^2\) 는 \(p = \delta_0\) 에서 기울기가 0이어서 \(R_1 = 0\) 이 되며 \(c \to \infty\) 와 \(x' = 1\) 에서의 생성자 그레이디언트 폭주를 허용합니다, 3 참조). \(R_2\) 를 추가하면 생성 샘플에서의 크리틱 그레이디언트도 유계로 묶입니다.

16.4.3 가치 함수에 미치는 그레이디언트 페널티의 영향

영중심 페널티 \(R_1 + R_2 = \gamma\,\mathbb{E}_m[\|\nabla_x D\|^2]\) 는 평형 근처에서 생성자가 최소화하는 발산을 어떻게 바꾸어 놓을까요?

16.4.3.1 국소 이차 근사와 가우스 이동

\(q = p\) 근처에서 최적 크리틱 \(D\) 는 작습니다. \(V_\ell(D)\) 안에서 \(D\) 에 대해 이차항까지 \(\ell(t) \approx \ell(0) + \ell'(0)t - \tfrac12|\ell''(0)|t^2\) 로 전개하면 다음을 얻습니다:

\[ \begin{aligned} V_\ell(D) &\approx 2\ell(0) + \ell'(0)\, \langle p - q,\, D \rangle - |\ell''(0)| \int m\, D^2 , \end{aligned} \]

여기서 \(\langle p - q, D \rangle = \mathbb{E}_p[D] - \mathbb{E}_q[D]\) 입니다. 작은 이동량 \(\mu\) 만큼 떨어진 두 단위 분산 가우스 분포 \(p = \mathcal{N}(0, 1)\), \(q = \mathcal{N}(\mu, 1)\) 과 선형 크리틱 \(D(x) = cx\) 를 생각해 봅시다. \(\mu\) 의 최고차항에서 \(\langle p - q, D \rangle = -c\mu\), \(\int m\,D^2 \approx c^2\) 이고 페널티는 \(\gamma\int m\,\|\nabla_x D\|^2 = \gamma c^2\) 입니다. \(c\) 에 대해 오목 이차 함수 \(-\ell'(0)\mu c - (|\ell''(0)| + \gamma)c^2\) 을 최대화하면 최적 기울기 \(c^\star = -\frac{\ell'(0)\mu}{2(|\ell''(0)| + \gamma)}\) 와 다음 가치를 얻습니다:

\[ \begin{aligned} \frac{\ell'(0)^2 \mu^2}{4\,(|\ell''(0)| + \gamma)} &= \frac{\mu^2}{4 + 16\gamma} \\ &\text{for the logistic loss, at slope } c^\star = -\frac{\mu}{1 + 4\gamma} . \end{aligned} \]

따라서 페널티는 크리틱의 기울기와 국소 가치를 모두 인수 \(1 + 4\gamma\) 만큼 수축시킵니다. \(\gamma = 0\) 에서는 \(\mu^2/4 \approx 2\,\mathrm{JS}(p, q)\) 가 복원되고 큰 \(\gamma\) 에서는 가치가 \(\mu^2/(16\gamma) = \tfrac{\ell'(0)^2}{4\gamma} W_2(p, q)^2\) 으로 스케일링됩니다. 아래에서 1차원 격자 위 뉴턴법으로 계산한 정확한 페널티 최적해와 이 닫힌 형태 근사를 비교해 검증합니다.

def penalized_value(p, q, gamma, x, newton_steps=30):
    """Value of the logistic game minus gamma E_m[D'^2], on a grid."""
    dx, m = x[1] - x[0], (p + q) / 2
    diff = np.diff(np.eye(len(x)), axis=0) / dx       # D -> D'
    K = 2 * gamma * dx * diff.T @ (((m[1:] + m[:-1]) / 2)[:, None] * diff)
    D = np.zeros_like(x)
    for _ in range(newton_steps):                     # Newton ascent on D
        s = 1 / (1 + np.exp(-D))                      # sigma(D)
        grad = (p * (1 - s) - q * s) * dx - K @ D     # gradient of the value
        neg_hess = np.diag(2 * m * s * (1 - s) * dx) + K  # minus its Hessian
        D = D + np.linalg.solve(neg_hess, grad)
    value = -(p * np.logaddexp(0, -D) + q * np.logaddexp(0, D)).sum() * dx
    return value - D @ K @ D / 2 + 2 * np.log(2)       # minus 2 l(0)

x = np.linspace(-8, 8, 401)
for mu in (0.2, 1, 3):
    p, q = [np.exp(-(x - c) ** 2 / 2) / np.sqrt(2 * np.pi) for c in (0, mu)]
    for gamma in (0, 0.01, 1, 10):
        exact = penalized_value(p, q, gamma, x)
        local = mu ** 2 / (4 + 16 * gamma)
        large = mu ** 2 / (16 * gamma) if gamma else np.inf
        print(f'mu {mu:>3}, gamma {gamma:>4}: exact {exact:.3e}, local '
              f'{local:.3e} ({local / exact:.2f}x), large-gamma {large:.3e} '
              f'({large / exact:.2f}x)')
mu 0.2, gamma    0: exact 9.950e-03, local 1.000e-02 (1.00x), large-gamma inf (infx)
mu 0.2, gamma 0.01: exact 9.566e-03, local 9.615e-03 (1.01x), large-gamma 2.500e-01 (26.13x)
mu 0.2, gamma    1: exact 1.996e-03, local 2.000e-03 (1.00x), large-gamma 2.500e-03 (1.25x)
mu 0.2, gamma   10: exact 2.438e-04, local 2.439e-04 (1.00x), large-gamma 2.500e-04 (1.03x)
mu   1, gamma    0: exact 2.228e-01, local 2.500e-01 (1.12x), large-gamma inf (infx)
mu   1, gamma 0.01: exact 2.135e-01, local 2.404e-01 (1.13x), large-gamma 6.250e+00 (29.27x)
mu   1, gamma    1: exact 4.818e-02, local 5.000e-02 (1.04x), large-gamma 6.250e-02 (1.30x)
mu   1, gamma   10: exact 6.120e-03, local 6.098e-03 (1.00x), large-gamma 6.250e-03 (1.02x)
mu   3, gamma    0: exact 1.054e+00, local 2.250e+00 (2.14x), large-gamma inf (infx)
mu   3, gamma 0.01: exact 1.012e+00, local 2.163e+00 (2.14x), large-gamma 5.625e+01 (55.57x)
mu   3, gamma    1: exact 3.909e-01, local 4.500e-01 (1.15x), large-gamma 5.625e-01 (1.44x)
mu   3, gamma   10: exact 6.862e-02, local 5.488e-02 (0.80x), large-gamma 5.625e-02 (0.82x)
def penalized_value(p, q, gamma, x, newton_steps=30):
    """Value of the logistic game minus gamma E_m[D'^2], on a grid."""
    dx, m = x[1] - x[0], (p + q) / 2
    diff = np.diff(np.eye(len(x)), axis=0) / dx       # D -> D'
    K = 2 * gamma * dx * diff.T @ (((m[1:] + m[:-1]) / 2)[:, None] * diff)
    D = np.zeros_like(x)
    for _ in range(newton_steps):                     # Newton ascent on D
        s = 1 / (1 + np.exp(-D))                      # sigma(D)
        grad = (p * (1 - s) - q * s) * dx - K @ D     # gradient of the value
        neg_hess = np.diag(2 * m * s * (1 - s) * dx) + K  # minus its Hessian
        D = D + np.linalg.solve(neg_hess, grad)
    value = -(p * np.logaddexp(0, -D) + q * np.logaddexp(0, D)).sum() * dx
    return value - D @ K @ D / 2 + 2 * np.log(2)       # minus 2 l(0)

x = np.linspace(-8, 8, 401)
for mu in (0.2, 1, 3):
    p, q = [np.exp(-(x - c) ** 2 / 2) / np.sqrt(2 * np.pi) for c in (0, mu)]
    for gamma in (0, 0.01, 1, 10):
        exact = penalized_value(p, q, gamma, x)
        local = mu ** 2 / (4 + 16 * gamma)
        large = mu ** 2 / (16 * gamma) if gamma else np.inf
        print(f'mu {mu:>3}, gamma {gamma:>4}: exact {exact:.3e}, local '
              f'{local:.3e} ({local / exact:.2f}x), large-gamma {large:.3e} '
              f'({large / exact:.2f}x)')
mu 0.2, gamma    0: exact 9.950e-03, local 1.000e-02 (1.00x), large-gamma inf (infx)
mu 0.2, gamma 0.01: exact 9.566e-03, local 9.615e-03 (1.01x), large-gamma 2.500e-01 (26.13x)
mu 0.2, gamma    1: exact 1.996e-03, local 2.000e-03 (1.00x), large-gamma 2.500e-03 (1.25x)
mu 0.2, gamma   10: exact 2.438e-04, local 2.439e-04 (1.00x), large-gamma 2.500e-04 (1.03x)
mu   1, gamma    0: exact 2.228e-01, local 2.500e-01 (1.12x), large-gamma inf (infx)
mu   1, gamma 0.01: exact 2.135e-01, local 2.404e-01 (1.13x), large-gamma 6.250e+00 (29.27x)
mu   1, gamma    1: exact 4.818e-02, local 5.000e-02 (1.04x), large-gamma 6.250e-02 (1.30x)
mu   1, gamma   10: exact 6.120e-03, local 6.098e-03 (1.00x), large-gamma 6.250e-03 (1.02x)
mu   3, gamma    0: exact 1.054e+00, local 2.250e+00 (2.14x), large-gamma inf (infx)
mu   3, gamma 0.01: exact 1.012e+00, local 2.163e+00 (2.14x), large-gamma 5.625e+01 (55.57x)
mu   3, gamma    1: exact 3.909e-01, local 4.500e-01 (1.15x), large-gamma 5.625e-01 (1.44x)
mu   3, gamma   10: exact 6.862e-02, local 5.488e-02 (0.80x), large-gamma 5.625e-02 (0.82x)

작은 이동량(\(\mu = 0.2\))에서는 모든 \(\gamma\) 에 걸쳐 이차 공식 \(\mu^2/(4 + 16\gamma)\) 이 정확한 수치 해와 1% 이내로 일치합니다.

16.4.3.2 쌍대 Sobolev 노름과 저역 통과 필터링

평형 근처의 일반 분포 \(p\) 와 \(q\) 에 대해서는 부분적분을 통해 그레이디언트 페널티를 \(\int m\,\|\nabla_x D\|^2 = \langle D, \mathcal{L}_m D \rangle\) 로 쓸 수 있습니다(여기서 \(\mathcal{L}_m D = -\nabla \cdot (m \nabla D)\) 는 \(m\)-가중 라플라시안입니다). 모든 함수 \(D\) 에 대해 국소 이차 근사를 최대화하면 다음을 얻습니다(5 참조):

\[ \begin{aligned} &\sup_{D} \Big\{ \ell'(0)\, \langle p - q,\, D \rangle - |\ell''(0)| \int m\, D^2 - \gamma \int m\, \| \nabla_x D \|^2 \Big\} \\ &\qquad = \frac{\ell'(0)^2}{4}\, \big\langle p - q,\, \big(|\ell''(0)|\, m + \gamma \mathcal{L}_m\big)^{-1} (p - q) \big\rangle . \end{aligned} \tag{16.4.7}\]

\(\gamma \to 0\) 일 때 이 식은 \(\tfrac{\ell'(0)^2}{4|\ell''(0)|} \int (p - q)^2/m \approx 2\,\mathrm{JS}(p, q)\) 로 축약됩니다. \(\gamma \to \infty\) 일 때는 제곱 쌍대 Sobolev 노름(dual Sobolev norm) \(\dot H^{-1}(m)\) 의 상수 배에 다가갑니다:

\[ \begin{aligned} &\frac{\ell'(0)^2}{4\gamma}\, \big\| p - q \big\|^2_{\dot H^{-1}(m)}, \\ &\|v\|_{\dot H^{-1}(m)} = \sup\Big\{ \langle v, D\rangle : \int m \|\nabla_x D\|^2 \leq 1 \Big\}. \end{aligned} \tag{16.4.8}\]

\(m\) 이 근사적으로 균등한 영역에서 \(\mathcal{L}_m\) 은 파수(wavenumber) \(\omega\) 의 푸리에 모드에 \(m\omega^2\) 을 곱하여 그 모드에 \(|\ell''(0)|^{-1}\) 대신 \((|\ell''(0)| + \gamma\omega^2)^{-1}\) 가중치를 부여합니다. 따라서 \(R_1 + R_2\) 는 \(p - q\) 에 대해 차단 길이 스케일이 \(\sqrt{\gamma / |\ell''(0)|}\)(로지스틱 손실에서는 \(2\sqrt{\gamma}\))인 공간적 저역 통과 필터(low-pass filter)로 작동합니다. \(\nabla_x D\) 의 단위가 길이 역수이므로 \(\gamma\) 의 단위는 길이 제곱이며 데이터 해상도 및 노름과 함께 스케일링됩니다. 또한 \(R_1 + R_2\) 는 \(m = (p+q)/2\) 의 지지집합 위에서만 \(\nabla_x D\) 에 페널티를 매기므로 서로소 지지집합 사이의 빈 공간 너머 그레이디언트는 여전히 신경망 크리틱의 매끄러움에 의존한다는 점에도 유의합시다(2 참조).

16.4.4 R3GAN 레시피

R3GAN (Huang 기타 2024년) 은 상대론적 페어링 손실(16.3절 의 d2l.rpgan_loss_D와 d2l.rpgan_loss_G)을 두 영중심 그레이디언트 페널티 \(R_1\) 및 \(R_2\) 와 결합합니다.

16.4.4.1 손실과 페널티 구현

비교를 위해 동일한 (critic, real, fake) 시그니처로 16.1절 의 고전적 로지스틱 판별자 손실과 비포화 생성자 손실을 구현한 gan_loss_D 및 gan_loss_G도 함께 저장합니다.

def gan_loss_D(critic, real, fake):
    """Logistic critic loss -E[log sigma(D(x))] - E[log sigma(-D(x'))]: the
    sum of two batch means, 2 log 2 at equilibrium, as update_D."""
    return F.softplus(-critic(real)).mean() + F.softplus(critic(fake)).mean()


def gan_loss_G(critic, real, fake):
    """Non-saturating generator loss -E[log sigma(D(x'))]; real is unused."""
    return F.softplus(-critic(fake)).mean()

def gan_loss_D(critic, real, fake):
    """Logistic critic loss -E[log sigma(D(x))] - E[log sigma(-D(x'))]: the
    sum of two batch means, 2 log 2 at equilibrium, as update_D."""
    return (jax.nn.softplus(-critic(real)).mean()
            + jax.nn.softplus(critic(fake)).mean())


def gan_loss_G(critic, real, fake):
    """Non-saturating generator loss -E[log sigma(D(x'))]; real is unused."""
    return jax.nn.softplus(-critic(fake)).mean()

페널티 함수는 인수 \(\gamma/2\) 를 곱하기 전 두 배치 위에서의 샘플별 제곱 입력 그레이디언트를 반환합니다. 입력 배치에 대해 크리틱 점수들의 합을 미분하는데, 각 점수가 자기 행에만 의존하므로 역전파 한 번으로 모든 샘플의 입력 그레이디언트를 얻습니다(행들을 서로 섞는 배치 정규화를 쓰면 이 성질이 깨집니다). 옵티마이저가 크리틱 매개변수에 대해 페널티를 다시 미분할 수 있도록 입력 그레이디언트는 자동 미분 그래프 안에 그대로 남겨 두며 샘플들은 상수로 고정합니다. 이 두 번째 미분 때문에 페널티가 포함된 크리틱 스텝은 대략 역전파 두 번만큼의 비용이 듭니다.

create_graph=True는 두 번째 미분을 위해 입력 그레이디언트의 계산 그래프를 유지하고 detach는 샘플들을 상수로 만듭니다.

합산된 점수에 대한 jax.grad가 입력 그레이디언트를 구하고 크리틱에 대해 페널티를 미분하면 그 주위로 두 번째 그레이디언트가 중첩되며, jax.lax.stop_gradient가 샘플들을 상수로 만듭니다.

def r1_r2_penalty(critic, real, fake):
    """Per-sample squared critic input gradients on real (R1) and fake (R2),
    before the gamma/2 scale."""
    def sq_grad_norm(x):
        x = x.detach().requires_grad_(True)
        grad, = torch.autograd.grad(critic(x).sum(), x, create_graph=True)
        return grad.reshape(x.shape[0], -1).pow(2).sum(dim=1)
    return sq_grad_norm(real), sq_grad_norm(fake)

def r1_r2_penalty(critic, real, fake):
    """Per-sample squared critic input gradients on real (R1) and fake (R2),
    before the gamma/2 scale."""
    def sq_grad_norm(x):
        # Rows are independent, so the gradient of the sum is per-sample
        grad = jax.grad(lambda x: critic(x).sum())(jax.lax.stop_gradient(x))
        return (grad.reshape(x.shape[0], -1) ** 2).sum(axis=1)
    return sq_grad_norm(real), sq_grad_norm(fake)

16.4.4.2 훈련 스텝

훈련 루프는 각 경기자의 스텝을 한 번씩 번갈아 밟습니다. critic_step은 생성 배치를 고정한 채 크리틱 손실 더하기 두 페널티 합의 \(\gamma/2\) 배에 대해 옵티마이저 스텝을 한 번 밟고, 루프가 크리틱의 가파르기를 기록할 수 있도록 손실과 함께 실제 및 생성 샘플에서의 제곱 입력 그레이디언트 배치 평균(\(\gamma/2\) 곱하기 전의 \(R_1\) 과 \(R_2\))을 반환합니다. 이어서 generator_step이 갱신된 크리틱에 맞서 생성자 손실 위에서 한 스텝을 밟습니다. 선택적 레이블 y는 16.6절 의 조건부 크리틱에 쓰입니다.

def critic_step(net_D, opt_D, loss_D, real, fake, gamma, y=None):
    """One critic step on loss_D + gamma/2 (R1 + R2); return the loss and
    the batch means of R1 and R2."""
    critic = net_D if y is None else lambda x: net_D(x, y)
    fake = fake.detach()  # the generator is held fixed
    r1, r2 = r1_r2_penalty(critic, real, fake)
    loss = loss_D(critic, real, fake)
    opt_D.zero_grad()
    (loss + gamma / 2 * (r1 + r2).mean()).backward()
    opt_D.step()
    return loss.detach(), r1.mean().detach(), r2.mean().detach()


def generator_step(net_G, opt_G, loss_G, net_D, real, z, y=None):
    """One generator step on loss_G against the critic; return the loss."""
    critic = net_D if y is None else lambda x: net_D(x, y)
    loss = loss_G(critic, real, net_G(z) if y is None else net_G(z, y))
    opt_G.zero_grad()
    loss.backward()
    opt_G.step()
    return loss.detach()

@nnx.jit(static_argnums=2)
def critic_step(net_D, opt_D, loss_D, real, fake, gamma, y=None):
    """One critic step on loss_D + gamma/2 (R1 + R2); return the loss and
    the batch means of R1 and R2."""
    def objective(net_D):
        critic = net_D if y is None else lambda x: net_D(x, y)
        r1, r2 = r1_r2_penalty(critic, real, fake)
        loss = loss_D(critic, real, fake)
        return (loss + gamma / 2 * (r1 + r2).mean(),
                (loss, r1.mean(), r2.mean()))
    (_, logs), grads = nnx.value_and_grad(objective, has_aux=True)(net_D)
    opt_D.update(net_D, grads)
    return logs


@nnx.jit(static_argnums=2)
def generator_step(net_G, opt_G, loss_G, net_D, real, z, y=None):
    """One generator step on loss_G against the critic; return the loss."""
    def objective(net_G):
        critic = net_D if y is None else lambda x: net_D(x, y)
        return loss_G(critic, real, net_G(z) if y is None else net_G(z, y))
    loss, grads = nnx.value_and_grad(objective)(net_G)
    opt_G.update(net_G, grads)
    return loss

손실 함수들은 컴파일된 스텝의 정적 인자이므로 각 손실 쌍마다 한 번만 컴파일되는 반면 \(\gamma\) 는 추적 대상이어서 재컴파일 없이 값을 바꿀 수 있습니다.

16.4.4.3 25-가우스 격자에서의 모드 커버리지

신경망에서 \(R_1 + R_2\) 와 쌍별 순위 매김이 모드 커버리지에 어떤 영향을 미치는지 시험하기 위해 2차원 가우스 \(5 \times 5\) 격자(간격 \(2.0\), 표준 편차 \(\sigma = 0.05\)) 위에서 3층 MLP 생성자(64차원 잠재 벡터, 256 ReLU 유닛 은닉층 두 개)와 3층 Leaky ReLU MLP 크리틱을 훈련합니다. 생성된 샘플 10,000개를 네 가지 지표로 평가합니다:

  1. 덮인 모드 수: 모드 내 안착 샘플들의 균등 몫(\(1/25\)) 중 최소 \(1/5\) 이상을 배정받은 모드의 개수.
  2. 모드 내 비율: 가장 가까운 모드 중심으로부터 \(3\sigma = 0.15\) 이내에 들어온 샘플 비율(참 분포에서는 \(98.9\%\)).
  3. 가장 가까운 중심까지의 평균 거리(참 분포에서는 \(\approx 0.06\)).
  4. 생성 샘플에서의 크리틱 가파르기 \(\mathbb{E}_q[\|\nabla_x D(x')\|^2]\).
def grid_centers(side=5, spacing=2.0):
    coords = (torch.arange(side, dtype=torch.float32) - (side - 1) / 2)
    gx, gy = torch.meshgrid(coords * spacing, coords * spacing, indexing='ij')
    return torch.stack([gx.reshape(-1), gy.reshape(-1)], dim=1)

def sample_modes(centers, n, width=0.05):
    idx = torch.randint(0, centers.shape[0], (n,), device=centers.device)
    return centers[idx] + width * torch.randn(n, 2, device=centers.device)
def grid_centers(side=5, spacing=2.0):
    coords = (jnp.arange(side) - (side - 1) / 2) * spacing
    gx, gy = jnp.meshgrid(coords, coords, indexing='ij')
    return jnp.stack([gx.reshape(-1), gy.reshape(-1)], axis=1)

def sample_modes(key, centers, n, width=0.05):
    k1, k2 = jax.random.split(key)
    idx = jax.random.randint(k1, (n,), 0, centers.shape[0])
    return centers[idx] + width * jax.random.normal(k2, (n, 2))

격자 centers 대비 생성 점 구름을 채점하기 위해 mode_stats는 각 샘플을 가장 가까운 모드 중심에 배정하고 덮인 모드 수, \(3\sigma\) 이내 샘플 비율, 최근접 중심까지의 평균 거리를 반환합니다:

def mode_stats(x, centers, width=0.05):
    """Modes covered (each holds a fifth of an even share of the on-mode
    samples), fraction within three widths, mean distance."""
    dist = np.linalg.norm(x[:, None] - centers[None], axis=-1)
    near, idx = dist.min(axis=1), dist.argmin(axis=1)
    on = near <= 3 * width
    counts = np.bincount(idx[on], minlength=len(centers))
    covered = (counts >= on.sum() / len(centers) / 5).sum()
    return covered, on.mean(), near.mean()
def mode_stats(x, centers, width=0.05):
    """Modes covered (each holds a fifth of an even share of the on-mode
    samples), fraction within three widths, mean distance."""
    dist = np.linalg.norm(x[:, None] - centers[None], axis=-1)
    near, idx = dist.min(axis=1), dist.argmin(axis=1)
    on = near <= 3 * width
    counts = np.bincount(idx[on], minlength=len(centers))
    covered = (counts >= on.sum() / len(centers) / 5).sum()
    return covered, on.mean(), near.mean()

train_grid는 회전 벡터장에서 양의 1차 모멘트 모멘텀이 안정 영역을 줄일 수 있다는 점을 반영해 R3GAN을 따라 \(\beta_1 = 0\) 인 Adam과 \(2 \times 10^{-3}\) 에서 \(2 \times 10^{-4}\) 로의 코사인 학습률 감쇠를 사용하여 10,000스텝(배치 크기 1,024) 동안 critic_step과 generator_step을 번갈아 실행합니다.

def train_grid(centers, loss_D, loss_G, gamma, steps=10000, lr=2e-3,
               batch=1024, latent=64, seed=0, checkpoints=8):
    """Alternate critic and generator steps; at each checkpoint record the
    on-mode fraction of 2,000 samples, and the critic loss and E_q|grad D|^2
    averaged over the steps since the previous checkpoint."""
    torch.manual_seed(seed)
    dev, grid = centers.device, centers.cpu().numpy()
    net_G = d2l.make_mlp([latent, 256, 256, 2], nn.ReLU()).to(dev)
    net_D = d2l.make_mlp([2, 256, 256, 1], nn.LeakyReLU(0.2)).to(dev)
    opt_G, opt_D = [torch.optim.Adam(net.parameters(),  # lr on the device
                                     torch.tensor(lr, device=dev),
                                     betas=(0.0, 0.99),
                                     capturable=dev.type == 'cuda')
                    for net in (net_G, net_D)]
    scheds = [torch.optim.lr_scheduler.CosineAnnealingLR(opt, steps, lr / 10)
              for opt in (opt_G, opt_D)]
    logs, every = torch.zeros(2, device=dev), steps // checkpoints

    def step():
        real = sample_modes(centers, batch)
        with torch.no_grad():
            fake = net_G(torch.randn(batch, latent, device=dev))
        loss, _, grad_q = critic_step(net_D, opt_D, loss_D, real, fake, gamma)
        logs.add_(torch.stack([loss, grad_q]))  # summed on the device
        z = torch.randn(batch, latent, device=dev)
        generator_step(net_G, opt_G, loss_G, net_D,
                       sample_modes(centers, batch), z)

    step, trace = d2l.cuda_graphed(step, dev), []
    for t in range(1, steps + 1):
        step()
        for sched in scheds:
            sched.step()
        if t % every == 0:                   # checkpoint
            with torch.no_grad():
                x = net_G(torch.randn(2000, latent, device=dev)).cpu().numpy()
            trace.append((mode_stats(x, grid)[1], *(logs / every).tolist()))
            logs.zero_()
    return net_G, trace
def train_grid(centers, loss_D, loss_G, gamma, steps=10000, lr=2e-3,
               batch=1024, latent=64, seed=0, checkpoints=8):
    """Alternate critic and generator steps; at each checkpoint record the
    on-mode fraction of 2,000 samples, and the critic loss and E_q|grad D|^2
    averaged over the steps since the previous checkpoint."""
    rngs = nnx.Rngs(seed)
    net_G = d2l.make_mlp([latent, 256, 256, 2], nnx.relu, rngs=rngs)
    net_D = d2l.make_mlp([2, 256, 256, 1], lambda x: nnx.leaky_relu(x, 0.2),
                         rngs=rngs)
    adam = optax.adam(optax.cosine_decay_schedule(lr, steps, alpha=0.1),
                      b1=0.0, b2=0.99)
    opt_G, opt_D = (nnx.Optimizer(net, adam, wrt=nnx.Param)
                    for net in (net_G, net_D))

    @nnx.jit
    def step(net_G, net_D, opt_G, opt_D, key, logs):
        k1, k2 = jax.random.split(key)
        z = jax.random.normal(k1, (2, batch, latent))    # critic, generator
        real = sample_modes(k2, centers, 2 * batch).reshape(2, batch, 2)
        fake = net_G(z[0])
        loss, _, grad_q = critic_step(net_D, opt_D, loss_D, real[0], fake,
                                      gamma)
        generator_step(net_G, opt_G, loss_G, net_D, real[1], z[1])
        return logs + jnp.stack([loss, grad_q])          # summed on the device

    step = nnx.cached_partial(step, net_G, net_D, opt_G, opt_D)
    trace, every, grid = [], steps // checkpoints, np.asarray(centers)
    keys = jax.random.split(rngs(), steps).reshape(checkpoints, every)
    for chunk in keys:                                   # one checkpoint each
        logs = jnp.zeros(2)
        for key in chunk:
            logs = step(key, logs)
        x = np.asarray(net_G(jax.random.normal(rngs(), (2000, latent))))
        trace.append((mode_stats(x, grid)[1], *(logs / every).tolist()))
    return net_G, trace

두 목적 함수(고전적 비포화 NS 대 pairing)와 \(\gamma = 0\)(무페널티) 및 \(\gamma = 1\)(\(R_1 + R_2\))을 교차한 \(2 \times 2\) 요인 실험을 각각 세 시드에 걸쳐 실행하고 \(\gamma = 10\) 의 과감쇠 실행도 함께 추가합니다.

centers, latent = grid_centers().to(d2l.try_gpu()), 64
ns, pairing = (gan_loss_D, gan_loss_G), (d2l.rpgan_loss_D, d2l.rpgan_loss_G)
arms = {'NS': (*ns, 0.0, 3), 'NS + R1 + R2': (*ns, 1.0, 3),
        'pairing': (*pairing, 0.0, 3), 'pairing + R1 + R2': (*pairing, 1.0, 3),
        'pairing + R1 + R2, gamma=10': (*pairing, 10.0, 1)}
runs = {name: [] for name in arms}               # per run: samples, trace
for name, (loss_D, loss_G, gamma, n_runs) in arms.items():
    for seed in range(n_runs):
        net_G, trace = train_grid(centers, loss_D, loss_G, gamma,
                                  latent=latent, seed=seed)
        with torch.no_grad():
            z = torch.randn(10000, latent, device=centers.device)
            runs[name].append((net_G(z).cpu().numpy(), trace))
grid = centers.cpu().numpy()
centers, latent = grid_centers(), 64
ns, pairing = (gan_loss_D, gan_loss_G), (d2l.rpgan_loss_D, d2l.rpgan_loss_G)
arms = {'NS': (*ns, 0.0, 3), 'NS + R1 + R2': (*ns, 1.0, 3),
        'pairing': (*pairing, 0.0, 3), 'pairing + R1 + R2': (*pairing, 1.0, 3),
        'pairing + R1 + R2, gamma=10': (*pairing, 10.0, 1)}
runs, key = {name: [] for name in arms}, jax.random.key(1)  # samples, trace
for name, (loss_D, loss_G, gamma, n_runs) in arms.items():
    for seed in range(n_runs):
        net_G, trace = train_grid(centers, loss_D, loss_G, gamma,
                                  latent=latent, seed=seed)
        key, subkey = jax.random.split(key)
        z = jax.random.normal(subkey, (10000, latent))
        runs[name].append((np.asarray(net_G(z)), trace))
grid = np.asarray(centers)

이제 크리틱의 최종 제곱 그레이디언트 노름 \(\mathbb{E}_q[\|\nabla_x D(x')\|^2]\) 옆에 각 실행에서 생성된 샘플 10,000개에 대한 mode_stats를 표로 정리합니다:

print(f'{"arm":28} run  modes  on-mode  distance  E_q|grad D|^2')
for name, results in runs.items():
    for seed, (x, trace) in enumerate(results):
        modes, on, dist = mode_stats(x, grid)
        print(f'{name:28} {seed:3}  {modes:2}/25  {on:7.2f}  {dist:8.2f}'
              f'  {trace[-1][2]:13.1e}')
arm                          run  modes  on-mode  distance  E_q|grad D|^2
NS                             0  16/25     0.70      0.20        1.7e+01
NS                             1  25/25     0.90      0.10        2.2e+00
NS                             2  24/25     0.76      0.16        5.6e+00
NS + R1 + R2                   0  25/25     0.77      0.15        8.9e-04
NS + R1 + R2                   1  25/25     0.83      0.13        6.8e-04
NS + R1 + R2                   2  25/25     0.86      0.11        3.6e-04
pairing                        0  25/25     0.82      0.13        3.9e+00
pairing                        1  15/25     0.76      0.17        1.2e+01
pairing                        2  23/25     0.80      0.15        5.1e+00
pairing + R1 + R2              0  25/25     0.86      0.12        3.3e-04
pairing + R1 + R2              1  25/25     0.89      0.09        1.9e-04
pairing + R1 + R2              2  25/25     0.85      0.12        5.0e-04
pairing + R1 + R2, gamma=10    0  23/25     0.19      0.46        1.2e-04
print(f'{"arm":28} run  modes  on-mode  distance  E_q|grad D|^2')
for name, results in runs.items():
    for seed, (x, trace) in enumerate(results):
        modes, on, dist = mode_stats(x, grid)
        print(f'{name:28} {seed:3}  {modes:2}/25  {on:7.2f}  {dist:8.2f}'
              f'  {trace[-1][2]:13.1e}')
arm                          run  modes  on-mode  distance  E_q|grad D|^2
NS                             0  12/25     0.81      0.15        1.0e+01
NS                             1  15/25     0.94      0.08        7.2e-01
NS                             2  24/25     0.74      0.17        5.9e+00
NS + R1 + R2                   0  25/25     0.67      0.21        2.4e-03
NS + R1 + R2                   1  25/25     0.87      0.11        4.1e-04
NS + R1 + R2                   2  25/25     0.79      0.14        8.2e-04
pairing                        0  20/25     0.64      0.24        3.1e+00
pairing                        1  17/25     0.78      0.15        1.3e+01
pairing                        2  23/25     0.77      0.16        6.3e+00
pairing + R1 + R2              0  25/25     0.79      0.15        8.2e-04
pairing + R1 + R2              1  25/25     0.70      0.19        1.4e-03
pairing + R1 + R2              2  25/25     0.79      0.15        7.4e-04
pairing + R1 + R2, gamma=10    0  25/25     0.28      0.39        9.0e-05

25개 모드 중심(grid) 위에 네 주요 실험군 첫 실행의 생성 샘플 3,000개를 찍어 보면 모드 커버리지 차이가 직접 드러납니다:

fig, axes = d2l.plt.subplots(1, 4, figsize=(10, 2.9))
for ax, name in zip(axes, list(runs)[:4]):
    x = runs[name][0][0][:3000]               # run 0; centers drawn last
    d2l.plot([x[:, 0], grid[:, 0]], [x[:, 1], grid[:, 1]],
             fmts=('C1.', 'C0x'), xlim=(-5, 5), ylim=(-5, 5), axes=ax)
    ax.set_title(name)
    ax.set_aspect('equal')
fig.tight_layout()

fig, axes = d2l.plt.subplots(1, 4, figsize=(10, 2.9))
for ax, name in zip(axes, list(runs)[:4]):
    x = runs[name][0][0][:3000]               # run 0; centers drawn last
    d2l.plot([x[:, 0], grid[:, 0]], [x[:, 1], grid[:, 1]],
             fmts=('C1.', 'C0x'), xlim=(-5, 5), ylim=(-5, 5), axes=ax)
    ax.set_title(name)
    ax.set_aspect('equal')
fig.tight_layout()

실험 결과는 그레이디언트 페널티와 페어링 손실 각각의 역할을 선명히 분리해 줍니다:

  • 모드 커버리지를 이끄는 그레이디언트 페널티: 페널티가 없으면(\(\gamma = 0\)) 크리틱 그레이디언트가 가파른 채로 남아(\(\mathbb{E}_q\|\nabla_x D\|^2 \in [0.7, 17]\)) 모드 커버리지가 불안정합니다(시드에 따라 12~25개 모드로 하락). \(\gamma = 1\) 의 \(R_1 + R_2\) 를 넣으면 크리틱 그레이디언트가 세 자릿수 감쇠(\(\sim 10^{-3}\))하며 NS와 pairing 양쪽 모두에서 모든 실행이 25개 모드 전체를 덮습니다.
  • 큰 \(\gamma\) 에서의 과감쇠: \(\gamma\) 를 \(10\) 으로 높이면 크리틱이 지나치게 평탄해져(\(\sim 10^{-4}\)) 수렴이 느려지므로 10,000스텝 뒤에도 샘플의 20%~30%만 모드의 \(3\sigma\) 이내에 안착합니다.

마지막으로 체크포인트 궤적을 점검해 보면 왜 잔잔한 크리틱 손실 곡선을 주의 깊게 해석해야 하는지 알 수 있습니다:

traces = {name: np.array(results[0][1]) for name, results in runs.items()}
for col, stat in enumerate(['on-mode fraction', 'critic loss']):
    print(f'{stat} of run 0 at every 1,250 steps')
    for name, trace in traces.items():         # trace: (checkpoint, stat)
        print(f'  {name:28}', ' '.join(f'{v:4.2f}' for v in trace[:, col]))
on-mode fraction of run 0 at every 1,250 steps
  NS                           0.01 0.03 0.08 0.16 0.29 0.54 0.69 0.72
  NS + R1 + R2                 0.02 0.03 0.09 0.08 0.26 0.64 0.68 0.79
  pairing                      0.02 0.07 0.17 0.31 0.50 0.73 0.74 0.82
  pairing + R1 + R2            0.02 0.01 0.04 0.16 0.50 0.74 0.81 0.86
  pairing + R1 + R2, gamma=10  0.02 0.03 0.02 0.05 0.09 0.09 0.16 0.21
critic loss of run 0 at every 1,250 steps
  NS                           1.35 1.21 1.04 1.00 1.01 1.03 1.05 1.07
  NS + R1 + R2                 1.38 1.37 1.36 1.37 1.38 1.38 1.38 1.38
  pairing                      0.68 0.65 0.57 0.57 0.60 0.62 0.63 0.64
  pairing + R1 + R2            0.68 0.68 0.67 0.68 0.69 0.69 0.69 0.69
  pairing + R1 + R2, gamma=10  0.69 0.70 0.69 0.69 0.69 0.69 0.69 0.69
traces = {name: np.array(results[0][1]) for name, results in runs.items()}
for col, stat in enumerate(['on-mode fraction', 'critic loss']):
    print(f'{stat} of run 0 at every 1,250 steps')
    for name, trace in traces.items():         # trace: (checkpoint, stat)
        print(f'  {name:28}', ' '.join(f'{v:4.2f}' for v in trace[:, col]))
on-mode fraction of run 0 at every 1,250 steps
  NS                           0.01 0.02 0.06 0.15 0.52 0.68 0.78 0.81
  NS + R1 + R2                 0.03 0.03 0.06 0.11 0.27 0.36 0.59 0.68
  pairing                      0.01 0.07 0.15 0.25 0.27 0.46 0.59 0.62
  pairing + R1 + R2            0.03 0.03 0.04 0.07 0.51 0.61 0.71 0.79
  pairing + R1 + R2, gamma=10  0.02 0.02 0.03 0.05 0.06 0.09 0.20 0.27
critic loss of run 0 at every 1,250 steps
  NS                           1.34 1.15 0.95 0.93 0.94 0.95 0.96 0.96
  NS + R1 + R2                 1.38 1.37 1.36 1.37 1.37 1.38 1.38 1.38
  pairing                      0.68 0.67 0.64 0.61 0.59 0.58 0.58 0.58
  pairing + R1 + R2            0.68 0.68 0.67 0.68 0.68 0.69 0.69 0.69
  pairing + R1 + R2, gamma=10  0.69 0.70 0.69 0.69 0.69 0.69 0.69 0.69

페널티가 적용된 실행들에서는 생성 샘플의 불과 1%~3%만 모드 위에 놓여 있는 맨 첫 번째 체크포인트부터 크리틱 손실이 평형값(NS는 \(2\log 2 \approx 1.39\), pairing은 \(\log 2 \approx 0.69\)) 근처에 자리 잡는데, 그레이디언트 페널티가 모든 곳에서 \(D(x)\) 를 작게 묶어 두기 때문입니다. 즉 평형 수준의 크리틱 손실은 크리틱이 평평하다는 뜻일 뿐 생성자가 수렴했다는 뜻은 아닙니다.

16.4.5 요약

2매개변수 Dirac-GAN(\(p = \delta_0, q_\theta = \delta_\theta, D_\psi(x) = \psi x\))에서 연속 시간 그레이디언트 흐름은 반지름이 일정한 원 궤도를 돌고, 동시 이산 스텝은 바깥 나선을 그리며 발산하고, 교대 이산 스텝은 유계 띠 안에 갇힌 채 머뭅니다. 영중심 그레이디언트 페널티 \(R_1 = \frac{\gamma}{2}\mathbb{E}_p[\|\nabla_x D(x)\|^2]\) 와 \(R_2 = \frac{\gamma}{2}\mathbb{E}_q[\|\nabla_{x'} D(x')\|^2]\) 를 빼 주면 모든 \(\gamma > 0\) 에 대해 야코비 행렬 고윳값이 열린 왼쪽 반평면(\(\operatorname{Re}(\nu_{1,2}) < 0\))으로 이동하여 평형이 국소 지수 안정해집니다. 평형 근처에서 \(R_1 + R_2\) 는 로지스틱 손실 아래 차단 길이 스케일 \(2\sqrt{\gamma}\) 를 가진 공간 저역 통과 필터로 \(p - q\) 에 작용하여 큰 스케일의 \(2\,\mathrm{JS}(p, q)\) 와 미세 스케일의 제곱 쌍대 Sobolev 노름 \(\|p - q\|_{\dot H^{-1}(m)}^2\) 사이를 보간합니다. 실험적으로 25-가우스 격자에서 \(\gamma = 1\) 의 \(R_1 + R_2\) 는 크리틱 가파르기를 세 자릿수 감쇠시키며 고전적 로지스틱 목적 함수와 상대론적 페어링 목적 함수 양쪽 모두에서 완전한 모드 커버리지를 달성합니다.

16.4.6 연습 문제

  1. [code] Dirac-GAN의 이산 시간 안정성. 스텝 크기 \(h\) 인 동시 경사 하강법은 \((\theta, \psi) \mapsto (\theta, \psi) + h\,\mathbf{u}(\theta, \psi)\) 로 사상합니다.
    1. \(\gamma = 0\) 일 때 \((0, 0)\) 에서의 이산 업데이트 야코비 행렬이 고윳값 \(1 \pm i\,h\,\ell'(0)\) 을 가지며, 모든 \(h > 0\) 에 대해 그 절댓값이 \(\sqrt{1 + h^2\ell'(0)^2} > 1\) 임을 보이십시오.
    2. \(\gamma > 0\) 일 때 고윳값은 식 16.4.6 의 \(\nu_{1,2}\) 에 대해 \(1 + h\nu_{1,2}\) 입니다. 부족감쇠 체제 \(\gamma < 2\ell'(0)\) 에서 이산 업데이트가 국소 안정할(\(|1 + h\nu_{1,2}| < 1\)) 필요충분조건이 \(h < \gamma / \ell'(0)^2\) 임을 보이십시오.
    3. \(h = 1.1\) 과 \(h = 1.3\) 에서 trajectory(euler_step, (0.1, 0.1), h, 3000, gamma=0.3)을 실행하여 \(\gamma = 0.3\)(\(\ell'(0) = \tfrac12\), 임곗값 \(h = 1.2\))에서 이 임곗값을 확인하십시오.
  2. Dirac-GAN에서의 페널티 최적 반응. \(\ell = \log \sigma\) 인 Dirac-GAN 위에서 \(V_\gamma(\theta) = \sup_\psi \{V(\theta, \psi) - \gamma\psi^2\}\) 를 고려합시다.
    1. 작은 \(\theta\) 에 대해 최대화 기울기가 \(\psi^\star \approx -\ell'(0)\theta / (2\gamma)\) 이고 \(V_\gamma(\theta) = 2\ell(0) + \frac{\ell'(0)^2}{4\gamma}\theta^2 + O(\theta^4)\) 이어서 \(W_2(\delta_0, \delta_\theta) = |\theta|\) 인 식 16.4.8 의 결과와 일치함을 보이십시오.
    2. 이제 \(D\) 가 \(\gamma\int m\,\|\nabla_x D\|^2\) 페널티를 받는 모든 미분 가능 함수 위에서 움직인다고 합시다. 점질량 \(p = \delta_0\) 과 \(q_\theta = \delta_\theta\)(\(\theta \neq 0\))에 대해 \(\sup_D \{V_\ell(D) - R_1 - R_2\} = 2\sup_t \ell(t)\) 가 \(\theta\) 와 무관함을 보이십시오. 그런데도 유한 신경망 크리틱은 왜 간격 너머로 0이 아닌 그레이디언트를 제공합니까?
  3. \(R_1\) 단독 페널티 대 \(R_1 + R_2\) 페널티. \(p = \delta_0\), \(q = \delta_1\), \(\ell = \log \sigma\) 라 두고 이차 크리틱 \(D_c(x) = -cx^2\)(\(c \geq 0\))을 고려합시다.
    1. \(D_c\) 에 대해 \(R_1\) 과 \(R_2\) 를 계산하고 \(V_\ell(D_c) - R_1\) 이 \(c\) 에 대해 순증가하므로 유한한 최대화점이 존재하지 않음을 보이십시오.
    2. 비포화 생성자 손실 \(-\log \sigma(D_c(x'))\) 아래에서 \(x' = 1\) 에서의 생성자 그레이디언트 크기가 \(c\) 에 따라 한없이 커지는 반면, \(R_1 + R_2\) 를 빼 주면 유한한 최대화점 \(c^\star < 1/(8\gamma)\) 를 얻음을 보이십시오.
  4. [code] Dirac-GAN에서의 교대 업데이트. ● 교대 업데이트는 \(\psi_{k+1} = \psi_k + h\,u_\psi(\theta_k, \psi_k)\) 에 이어 \(\theta_{k+1} = \theta_k + h\,u_\theta(\theta_k, \psi_{k+1})\) 를 적용합니다.
    1. \(\gamma = 0\) 일 때 \((0, 0)\) 에서 결합 업데이트를 선형화하여 야코비 행렬의 행렬식이 \(1\) 이고 고윳값들이 단위 원 위에 놓일 필요충분조건이 \(h\,\ell'(0) \leq 2\) 임을 보이십시오.
    2. \(h \in \{0.2, 1, 3, 5\}\) 에 대해 \(\gamma = 0\) 에서 trajectory(alt_step, (0.1, 0.1), h, 10**5)를 실행하고 마지막 \(10^4\) 스텝 동안의 최소·최대 반지름을 기록한 뒤 \(h = 0.2\), \(\gamma = 0.3\) 인 경우와 비교하십시오.
  5. [code] 국소 이차 가치와 저역 통과 필터링. ● \(\mathcal{L}_m D = -\nabla \cdot (m \nabla D)\) 에 대해 \(\mathcal{A} = |\ell''(0)|\,m + \gamma\mathcal{L}_m\) 이라 씁시다.
    1. 부분적분을 이용해 다음 등식을 보이고,

      \[|\ell''(0)|\int m\,D^2 + \gamma\int m\,\|\nabla_x D\|^2 = \langle D, \mathcal{A}D \rangle\]

      반직선 \(t D_0\) 를 따라 최대화한 뒤 코시–슈바르츠 부등식을 적용해 식 16.4.7 의 결과를 유도하십시오.

    2. \(p = \mathcal{N}(0, 1)\) 이고 \(q(x) = p(x)(1 + 0.1\sin(\omega x))\) 라 합시다. penalized_value를 사용해 \(\omega \in \{0.5, 2, 8\}\) 에 대해 \(\gamma = 0\) 무페널티 가치 대비 \(\gamma \in \{0.01, 0.1, 1\}\) 페널티 가치의 비율을 계산하고 균등-\(m\) 푸리에 감쇠 인수 \((1 + 4\gamma\omega^2)^{-1}\) 과 비교하십시오.

  6. [code] Dirac-GAN에서의 1중심 페널티 동역학. ● 크리틱 목적 함수에서 1중심 페널티 \(\frac{\gamma}{2}(|\psi| - 1)^2\) 을 뺀 WGAN 선형 보수 \(\ell(t) = t\)(\(\ell'(0) = 1\))를 고려합시다.
    1. \(\psi \neq 0\) 에서 동시 그레이디언트 장이 결코 0이 되지 않음을 보이고 \(\psi \to 0^\pm\) 일 때 단측 극한이 0이 되는 생성자 위치 \(\theta\) 들을 구하십시오.
    2. 1중심 페널티를 쓰도록 dirac_field를 수정하고 \(\gamma = 1\) 및 \(\gamma = 3\) 에서 \(h = 0.01\) 로 \((1, 1)\) 부터 40,000스텝 동안 trajectory를 실행해 \(\gamma = 3\) 일 때 생성자가 \(\theta = 3\) 에서 멈춤을 확인하십시오.

토론