16.4  勾配ペナルティと収束

16.1 節 の Fashion-MNIST 実験では、識別器損失も生成器損失も理論上の平衡値には落ち着かなかった。交互勾配降下法は収束が遅いだけなのか、それとも平衡点に到達することなくその周囲を際限なく周回しうるのだろうか。16.1 節 から 16.3 節 までの母集団ダイバージェンスの解析では、クリティックが厳密な最適解 \(D^\star\) にあるときのミニマックス目的関数を特徴づけた。しかし実際には、両方のネットワークが同時または交互に小さな勾配ステップを踏み、一方の更新がもう一方の目的関数を絶えず変化させる。

勾配訓練のダイナミクスを直接解析するため、Mescheder ほか (2018年) は点質量のデータ分布、点質量の生成器、および線形クリティックからなる最小限の 2 パラメータ問題である Dirac-GAN を導入した。このような 2 パラメータ系においてさえ、正則化なしの勾配降下法は収束しない。一方で、クリティックの入力勾配の二乗ノルムにペナルティ(\(R_1\) と \(R_2\))を課すと、平衡点は局所漸近安定(locally asymptotically stable)になる。これらのゼロ中心勾配ペナルティ(zero-centered gradient penalty)を 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\) とする(したがって \(q_\theta = p\) となるのは \(\theta = 0\) のとき、かつそのときに限る)。また、クリティックをバイアスなしの線形関数 \(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(t) = \log \sigma(t)\) を用いる。この関数は \(\ell'(t) = \sigma(-t) > 0\) および \(\ell''(t) = -\sigma(t)\sigma(-t) < 0\) を満たし、\(\ell'(0) = \tfrac12\)、\(\ell''(0) = -\tfrac14\) である。

任意の \(\theta \neq 0\) に対して、\(p\) と \(q_\theta\) の台(support)は互いに素である。そのため、\(V(\theta, \psi)\) を \(\psi\) について最大化すると \(\psi\theta \to -\infty\) となり、定数 \(\sup_\psi V(\theta, \psi) = \ell(0)\) がすべての \(\theta \neq 0\) に対して得られる結果、\(\theta\) に関する勾配はゼロになる。

16.4.1.2 連続時間における非減衰振動

勾配訓練では、\(\sup_\psi V(\theta, \psi)\) を直接解く代わりに、現在の値から \(\theta\) と \(\psi\) を少しずつ更新する。式 16.4.1 の唯一の停留点(stationary point)は平衡点 \((\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} \]

あらゆる軌跡は、\((0, 0)\) を中心とする一定半径の閉じた円を描く(これは任意の狭義単調増加な利得 \(\ell\) に対して成り立つ)。すなわち、生成器のパラメータ \(\theta\) は決して収束することなく、\(0\) をまたいで前後に振動し続ける。

式 16.4.2 を \((\theta, \psi) = (0, 0)\) の周りで線形化すると(38.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\) を更新し、続いて \(\theta\) を更新後の \(\psi\) を用いて更新する手法)は、これよりわずかに良い挙動を示す。\((0, 0)\) の近傍では、各半ステップが面積保存の線形せん断となるため、合成されたヤコビ行列の行列式は \(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\) へと移動させなければならない。平衡時のクリティックは平坦でなければならないため(\(\nabla_x D^\star(x) = 0\) が \(q = p\) のときに成り立つ)、クリティックの入力勾配の二乗ノルムにペナルティを課せば、平衡 \(q = p\) をずらすことなくクリティックに減衰を加えられる。

Mescheder ほか (2018年) は、2 つのゼロ中心勾配ペナルティとして \(R_1\)(実データ \(x \sim p\) 上で評価)と \(R_2\)(生成サンプル \(x' \sim q\) 上で評価)を次のように定義している。

\[ \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\) を引くと、線形減衰項 \(-\gamma\psi\) が \(\dot\psi\) に加わる(\(-2\gamma\psi\) となるのは \(R_1\) と \(R_2\) の両方を含めた場合である)。

\[ \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)\) は局所指数安定(locally exponentially stable)である。特性多項式 \(\nu^2 + \gamma\nu + \ell'(0)^2 = 0\) は減衰調和振動子(38.1.2.5 節)のものと同一であり、次の 3 つのレジームを持つ。

  1. 不足減衰(underdamped、\(\gamma < 2\ell'(0)\)):実部 \(-\gamma/2\) を持つ複素共役固有値となり、軌跡は内向きに渦を巻く(同時オイラーステップのもとでは \(h < \gamma / \ell'(0)^2\) のときに収束する。演習問題 1)。
  2. 臨界減衰(critically damped、\(\gamma = 2\ell'(0)\)、すなわちロジスティック損失では \(\gamma = 1\)):重複実固有値 \(\nu = -\ell'(0)\) を持ち、最も速い非振動的減衰をもたらす。
  3. 過減衰(overdamped、\(\gamma > 2\ell'(0)\)):2 つの負の実固有値を持ち、遅いモード \(\nu \approx -\ell'(0)^2/\gamma\) は \(\gamma\) が大きくなるほどゆっくりと減衰する。

16.4.2.2 相図

式 16.4.2 を \((\theta_0, \psi_0) = (1, 1)\)(初期半径 \(\sqrt{2} \approx 1.41\))から、4 次のルンゲ・クッタ法(rk4_step)、同時前進オイラー法(euler_step)、および交互勾配更新(alt_step)を用いて数値積分し、これら 4 つのレジームを検証する。

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)

すべての軌道は赤い点 \((\theta, \psi) = (1, 1)\)(黒い十字で示す平衡点からの距離 \(\sqrt 2 \approx 1.41\))から出発する。左のパネルは連続時間フローを示す。中央のパネルは、ステップサイズ \(h = 0.2\) による 300 回の同時ステップと 2,000 回の交互ステップを示す。右のパネルは、ペナルティを加えた同じステップサイズによる 300 回の同時ステップを、不足減衰レジームの \(\gamma = 0.3\) と臨界減衰の \(\gamma = 1\) について示す。

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]

相図から 4 つの予測すべてが確認できる。連続時間フロー(RK4)は半径 \(1.41\) の円上を周回し、同時オイラーステップは 300 ステップ後に半径 \(2.87\) まで外向きに渦を巻いて広がり、交互ステップは \([1.34, 1.42]\) の内部を周回する。そしてゼロ中心ペナルティを加えると、同時オイラーステップは原点へと直接収束する(半径 \(6.5 \times 10^{-4}\) に不足減衰 \(\gamma = 0.3\) で到達し、\(7 \times 10^{-12}\) に臨界減衰 \(\gamma = 1\) で到達する)。

16.4.2.3 一般のネットワークに対する局所収束とペナルティの比較

Mescheder ほか (2018年) は、この局所安定性解析を 2 パラメータの Dirac-GAN から一般のニューラルネットワークへと拡張した。すなわち、生成器がデータ分布 \(p\) を表し、クリティックが \(\operatorname{supp}(p)\) 上で平坦であるような平衡の近傍において、クリティックが生成器の一次摂動を検出するのに十分な局所表現能力を備えていれば、\(R_1\) または \(R_2\)(および \(\ell'(0) \neq 0, \ell''(0) < 0\) を満たす狭義凹損失)を用いた同時および交互勾配更新は、平衡多様体へ指数関数的に収束する(Huang ほか (2024年) は相対論的ペアリング目的関数に対しても同様の局所定理を確立している)。

この解析から、実践上の 2 つの設計選択の理由も説明できる。

  • ゼロ中心(\(R_1, R_2\))対 1 中心(WGAN-GP)ペナルティ:WGAN-GP は \((\|\nabla_x D\| - 1)^2\) にペナルティを課すため、\(q = p\) のときでさえクリティックに傾き 1 を維持することを強制する。線形利得 \(\ell(t) = t\) を持つ Dirac-GAN では、1 中心ペナルティによって \(\theta = 0\) への収束が妨げられる。\(\gamma \geq 2\) のときはワッサースタイン勾配とペナルティが釣り合う \(|\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\) において傾きがゼロであるため \(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\) は小さい。\(\ell(t) \approx \ell(0) + \ell'(0)t - \tfrac12|\ell''(0)|t^2\) により \(D\) の 2 次まで \(V_\ell(D)\) の内部を展開すると、次式が得られる。

\[ \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]\) である。2 つの単位分散ガウス分布 \(p = \mathcal{N}(0, 1)\) と \(q = \mathcal{N}(\mu, 1)\)(小さなシフト \(\mu\) だけ離れている)および線形クリティック \(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\) となる。凹二次関数 \(-\ell'(0)\mu c - (|\ell''(0)| + \gamma)c^2\) を \(c\) について最大化すると、最適な傾き \(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\) 分の 1 に縮小する。\(\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\))、二次近似式 \(\mu^2/(4 + 16\gamma)\) はすべての \(\gamma\) にわたって厳密な数値解と 1% 以内の誤差で一致する。

16.4.3.2 双対ソボレフノルムとローパスフィルタリング

平衡近傍にある一般の分布 \(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\) のときは、双対ソボレフノルム(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\) は波数 \(\omega\) のフーリエモードに \(m\omega^2\) を掛けるため、そのモードの重み付けは \((|\ell''(0)| + \gamma\omega^2)^{-1}\) となる(ペナルティなしの \(|\ell''(0)|^{-1}\) に代わる)。したがって、\(R_1 + R_2\) は \(p - q\) に対する空間的なローパスフィルタとして働き、そのカットオフ長さスケールは \(\sqrt{\gamma / |\ell''(0)|}\)(ロジスティック損失では \(2\sqrt{\gamma}\))となる。\(\nabla_x D\) は長さの逆数の単位を持つため、\(\gamma\) は長さの二乗の単位を持ち、データの解像度やノルムに応じてスケールする。なお、\(R_1 + R_2\) が \(\nabla_x D\) にペナルティを課すのは \(m = (p+q)/2\) の台の上のみである。互いに素な台の間に広がる空白領域をまたぐ勾配は、依然としてニューラルネットワークであるクリティックの滑らかさに依存する(演習問題 2)。

16.4.4 R3GAN レシピ

R3GAN (Huang ほか 2024年) は、相対論的ペアリング損失(d2l.rpgan_loss_D および d2l.rpgan_loss_G、16.3 節)と両方のゼロ中心勾配ペナルティ \(R_1\)、\(R_2\) を組み合わせた手法である。

16.4.4.1 損失とペナルティの実装

比較のため、gan_loss_D と gan_loss_G(16.1 節 の古典的なロジスティック識別器損失と非飽和生成器損失)も同じ (critic, real, fake) シグネチャで実装し、保存しておく。

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\) を掛ける前の、両バッチにおけるサンプルごとの二乗入力勾配を返す。ここではクリティックのスコアの和を入力バッチに関して微分する。各スコアはそれぞれの行のみに依存するため、1 回の逆伝播ですべてのサンプルの入力勾配が求まる(行同士を混合するバッチ正規化を用いると、この性質は成り立たなくなる)。入力勾配は自動微分の計算グラフ内に保持されるため、オプティマイザはクリティックのパラメータに関してペナルティをさらに微分できる。このときサンプル自体は定数として固定する。2 回目の微分を伴うため、ペナルティ付きクリティックステップの計算コストはおよそ 2 回分の逆伝播に相当する。

create_graph=True によって 2 回目の微分のために計算グラフ内に入力勾配を保持し、detach によってサンプルを定数として扱う。

スコアの和に対する jax.grad によって入力勾配が得られ、クリティックに関してペナルティを微分するとその外側に 2 回目の勾配計算が入れ子になる。また、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 訓練ステップ

訓練ループでは、各プレイヤーのステップを 1 回ずつ交互に実行する。critic_step は生成バッチを固定した状態で、クリティック損失に両ペナルティの \(\gamma/2\) 倍を加えた目的関数に対してオプティマイザを 1 ステップ進め、損失ならびに実サンプルと生成サンプルにおける二乗入力勾配のバッチ平均(\(R_1\) と \(R_2\) の \(\gamma/2\) を掛ける前の値)を返す。これにより、訓練ループ内でクリティックの急峻さを記録できる。続いて generator_step が、更新後のクリティックに対する生成器損失について 1 ステップ進める。オプションのラベル 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

損失関数はコンパイルされるステップ関数の静的引数であるため、損失のペアごとに 1 回だけコンパイルされる。一方、\(\gamma\) はトレースされるため、再コンパイルなしに変更できる。

16.4.4.3 25 ガウスグリッドにおけるモード被覆

ニューラルネットワークにおけるモード被覆(mode coverage)に \(R_1 + R_2\) とペアワイズランキングがどう影響するかを検証するため、2 次元ガウス分布の \(5 \times 5\) グリッド(間隔 \(2.0\)、標準偏差 \(\sigma = 0.05\))上で、3 層の MLP 生成器(64 次元の潜在変数、256 個の ReLU ユニットからなる 2 つの隠れ層)と 3 層の Leaky ReLU MLP クリティックを訓練する。生成された 10,000 個のサンプルを次の 4 つの評価指標で評価する。

  1. 被覆モード数(covered modes):モード上サンプルのうち、少なくとも \(1/5\) 倍(均等配分 \(1/25\) に対する比率)を受け取ったモードの数。
  2. モード上サンプル比率(on-mode fraction):最近傍のモード中心から \(3\sigma = 0.15\) 以内に入るサンプルの割合(真の分布では \(98.9\%\))。
  3. 最近傍の中心までの平均距離(真の分布では \(\approx 0.06\))。
  4. 生成サンプルにおけるクリティックの急峻さ(critic steepness)\(\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 は critic_step と generator_step を 10,000 ステップ(バッチサイズ 1,024)交互に実行する。オプティマイザには \(\beta_1 = 0\) の Adam(回転ベクトル場において正の一次モーメントのモメンタムは安定領域を狭めうるため、R3GAN に倣う)を用い、\(2 \times 10^{-3}\) から \(2 \times 10^{-4}\) へのコサイン学習率減衰を適用する。

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

ここでは \(2 \times 2\) の要因実験として、2 つの目的関数(古典的な非飽和型 NS と pairing)に \(\gamma = 0\)(ペナルティなし)および \(\gamma = 1\)(\(R_1 + R_2\))を掛け合わせた各条件を 3 シードずつ実行し、さらに過減衰の実行(\(\gamma = 10\))を 1 つ加える。

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)

各実行から生成された 10,000 個のサンプルに対する mode_stats の結果を、クリティックの最終的な二乗勾配ノルム \(\mathbb{E}_q[\|\nabla_x D(x')\|^2]\) と並べて表にまとめる。

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

主要な 4 つの実験アームそれぞれの最初の実行から生成された 3,000 個のサンプルを、25 個のモード中心(grid)と重ねてプロットすると、モード被覆の違いが直接見て取れる。

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 モードに落ち込む)。\(R_1 + R_2\) を \(\gamma = 1\) で課すと、クリティックの勾配は 3 桁減衰し(\(\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

ペナルティ付きの実行では、クリティック損失は最初のチェックポイントから平衡値(NS では \(2\log 2 \approx 1.39\)、pairing では \(\log 2 \approx 0.69\))の付近に留まる。これは生成サンプルのわずか 1〜3% しかモード上に乗っていない段階でさえ生じる現象であり、勾配ペナルティが至るところで \(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]\) を差し引くと、ヤコビ行列の固有値が開左半平面(\(\operatorname{Re}(\nu_{1,2}) < 0\))へとすべての \(\gamma > 0\) に対して移動し、平衡点は局所指数安定となる。平衡の近傍では、\(R_1 + R_2\) は \(p - q\) に対する空間ローパスフィルタ(ロジスティック損失のもとでのカットオフ長さスケールは \(2\sqrt{\gamma}\))として働き、大きなスケールでの \(2\,\mathrm{JS}(p, q)\) と細かなスケールでの二乗双対ソボレフノルム \(\|p - q\|_{\dot H^{-1}(m)}^2\) の間を補間する。実験的にも、25 ガウスグリッドにおいて \(R_1 + R_2\)(\(\gamma = 1\))はクリティックの急峻さを 3 桁減衰させ、古典的なロジスティック目的関数と相対論的ペアリング目的関数の双方で完全なモード被覆を達成した。

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)\) を持ち、その絶対値が \(\sqrt{1 + h^2\ell'(0)^2} > 1\)(任意の \(h > 0\) に対して)となることを示せ。
    2. \(\gamma > 0\) のとき、固有値は \(1 + h\nu_{1,2}\)(ただし \(\nu_{1,2}\) は 式 16.4.6 のもの)となる。不足減衰レジーム \(\gamma < 2\ell'(0)\) において、離散更新が局所安定(\(|1 + h\nu_{1,2}| < 1\))となるのは \(h < \gamma / \ell'(0)^2\) のとき、かつそのときに限ることを示せ。
    3. \(\gamma = 0.3\)(\(\ell'(0) = \tfrac12\)、しきい値 \(h = 1.2\))におけるこのしきい値を、trajectory(euler_step, (0.1, 0.1), h, 3000, gamma=0.3) を \(h = 1.1\) と \(h = 1.3\) で実行して検証せよ。
  2. Dirac-GAN におけるペナルティ付き最適応答。 Dirac-GAN において \(V_\gamma(\theta) = \sup_\psi \{V(\theta, \psi) - \gamma\psi^2\}\)(\(\ell = \log \sigma\))を考える。
    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)\) となり、式 16.4.8 において \(W_2(\delta_0, \delta_\theta) = |\theta|\) とした結果に一致することを示せ。
    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\) に依存しないことを示せ。有限サイズのニューラルネットワークのクリティックが、それでもこの隔たりをまたいで非ゼロの勾配を与えるのはなぜか。
  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. \(R_1\) と \(R_2\) を \(D_c\) に対して計算し、\(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. 合成された更新を \((0, 0)\) の周りで(\(\gamma = 0\) として)線形化し、そのヤコビ行列の行列式が \(1\) であり、固有値が単位円上に乗るのは \(h\,\ell'(0) \leq 2\) のとき、かつそのときに限ることを示せ。
    2. trajectory(alt_step, (0.1, 0.1), h, 10**5) を \(\gamma = 0\) のもとで \(h \in \{0.2, 1, 3, 5\}\) に対して実行し、最後の \(10^4\) ステップにおける最小半径と最大半径を記録して、\(\gamma = 0.3\)(\(h = 0.2\))の場合と比較せよ。
  5. [code] 局所二次近似値とローパスフィルタリング。 ● \(\mathcal{A} = |\ell''(0)|\,m + \gamma\mathcal{L}_m\)(ただし \(\mathcal{L}_m D = -\nabla \cdot (m \nabla D)\))とおく。
    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 を用いて、\(\gamma \in \{0.01, 0.1, 1\}\) におけるペナルティ付きの値と \(\gamma = 0\) におけるペナルティなしの値との比を \(\omega \in \{0.5, 2, 8\}\) について計算し、一様な \(m\) を仮定したフーリエ減衰因子 \((1 + 4\gamma\omega^2)^{-1}\) と比較せよ。

  6. [code] Dirac-GAN における 1 中心ペナルティのダイナミクス。 ● WGAN の線形利得 \(\ell(t) = t\)(\(\ell'(0) = 1\))において、クリティックの目的関数から 1 中心ペナルティ \(\frac{\gamma}{2}(|\psi| - 1)^2\) を差し引いた系を考える。
    1. 同時勾配場が \(\psi \neq 0\) では決してゼロにならないことを示し、生成器のパラメータ位置 \(\theta\) のうち、\(\psi \to 0^\pm\) としたときの片側極限がゼロになるものを求めよ。
    2. 1 中心ペナルティを用いるように dirac_field を変更し、trajectory を \((1, 1)\) から \(h = 0.01\) で 40,000 ステップ(\(\gamma = 1\) および \(\gamma = 3\))実行して、\(\gamma = 3\) では生成器が \(\theta = 3\) で停滞することを検証せよ。

ディスカッション