第25回:Deep Ritz法を作る — FEMのenergy minimisationからneural trial spaceへ

ChatGPTで作る有限要素プログラム入門 Season 3 第1回(通算第25回)

はじめに――Season 3では「mesh-free」をそのまま信じない

Season 1・2では,有限要素法を mesh geometry,DoF,trace,Piola transform,stability,consistency,certification から組み立てました. Season 3では,その視点をDeep Ritz,PINNs,operator learningへ移します.

出発点となる問いは

\[ \boxed{ \text{meshを使わなくても,geometryの問題は本当に消えるのか?} } \tag{1} \]

です.

結論を先に言えば,消えません. elementの代わりに

\[ \boxed{ \text{quadrature points}, \quad \text{collocation points}, \quad \text{sensor points} } \tag{2} \]

の配置が近似の見え方を決めます.

Season 3の原則
メッシュを捨てても,点はどこかに置かなければならない.
FEMではelement geometryを監査した. Season 3ではsampling geometryを監査する.

1.Poisson問題をRitz minimisationとして書く

まず最も単純な1次元Poisson問題

\[ -u''(x)=f(x), \qquad 0<x<1, \qquad u(0)=u(1)=0 \tag{3} \]

を考えます.

energy spaceは \[ V=H_0^1(0,1) \] で,energy functionalを

\[ \boxed{ E(v) = \frac12 \int_0^1 |v'(x)|^2\,dx - \int_0^1 f(x)v(x)\,dx } \tag{4} \]

とします.

2.weak solutionはenergy minimiserである

\(u\in V\) がPoisson problemのweak solutionなら

\[ \int_0^1 u'v'\,dx = \int_0^1 fv\,dx \qquad \forall v\in V. \tag{5} \]

そして

\[ \boxed{ u = \operatorname*{arg\,min}_{v\in V} E(v). } \tag{6} \]

これがRitz principleです. Deep Ritzは,このvariational principleをneural networkへ移した方法です.

3.linear Poissonではenergy gapがerrorそのものになる

任意の \(v\in V\) に対して

\[ \boxed{ E(v)-E(u) = \frac12 \int_0^1 |v'-u'|^2\,dx. } \tag{7} \]

つまり

\[ \boxed{ \|v-u\|_{H_0^1\text{-energy}} = \sqrt{ 2\bigl(E(v)-E(u)\bigr) }. } \tag{8} \]

これはDeep Ritzを監査するうえで非常に強いidentityです. ただし後で見るように, 実際にoptimizerが最小化するのはcontinuous energy \(E\) ではなく sampled energy \(E_N\) です.

4.FEMのRitz法では何をしていたのか

conforming FEMではfinite-dimensional linear space

\[ V_h = \operatorname{span} \{ \phi_1,\ldots,\phi_M \} \subset H_0^1(0,1) \tag{9} \]

を選び,

\[ \boxed{ u_h = \operatorname*{arg\,min}_{v_h\in V_h} E(v_h). } \tag{10} \]

この最小化はlinear system \[ K\boldsymbol u=\boldsymbol f \] へ落ちます.

5.Deep Ritzではlinear spaceをneural trial manifoldに置き換える

neural network \(N_\theta(x)\) を使って

\[ \boxed{ \mathcal V_\Theta = \{ u_\theta: \theta\in\Theta \} } \tag{11} \]

というnonlinear trial familyを作ります.

Deep Ritzの理想形は

\[ \boxed{ \theta^\ast \in \operatorname*{arg\,min}_{\theta\in\Theta} E(u_\theta). } \tag{12} \]

したがって

\[ \boxed{ \text{FEM} : \text{linear finite-dimensional space}, \qquad \text{Deep Ritz} : \text{nonlinear finite-dimensional manifold} } \tag{13} \]

と見ることができます.

6.boundary conditionはhard constraintで入れる

今回は \[ u(0)=u(1)=0 \] をpenaltyにせず,

\[ \boxed{ u_\theta(x) = x(1-x)N_\theta(x) } \tag{14} \]

と置きます.

すると任意のparameter \(\theta\) に対し

\[ u_\theta(0)=u_\theta(1)=0. \tag{15} \]

これによりboundary penalty weightという別の要因を排除し, energy discretisationとpoint placementに集中できます.

7.ここでFEMとの大きな違いが一つ現れる

\(V_h\) はlinear spaceなので \[ u_h+tv_h\in V_h \] が成り立ちます. 一方,neural trial family \(\mathcal V_\Theta\) は一般にlinear spaceではありません.

従ってstandard Galerkin orthogonality

\[ a(u-u_h,v_h)=0 \qquad \forall v_h\in V_h \tag{16} \]

をそのままneural trial manifoldへ移してはいけません.

Deep Ritzの基本構造は Galerkin orthogonalityではなくenergy minimisation です.

8.実際にはcontinuous energyを計算できない

式 (4) はintegralを含みます. network trainingでは quadrature points \[ x_1,\ldots,x_N \] とweights \[ w_1,\ldots,w_N \] を用いて

\[ \boxed{ E_N(u_\theta) = \sum_{i=1}^N w_i \left[ \frac12 |u_\theta'(x_i)|^2 - f(x_i)u_\theta(x_i) \right]. } \tag{17} \]

これを最小化します.

9.Deep Ritzの点配置はquadrature geometryである

したがってDeep Ritzにおけるtraining pointsは, PINNsのcollocation pointsとは役割が少し違います.

\[ \boxed{ \text{Deep Ritz point placement} = \text{energy integralをどう観測するか} } \tag{18} \]

です.

point setが悪ければ, optimizerは \(E\) ではなく 歪んだ \(E_N\) を忠実に最小化します.

10.「training lossが小さい」はcontinuous energyが小さいとは限らない

trainingで分かるのは

\[ E_N(u_\theta) \]

だけです. 本当に知りたいのは

\[ E(u_\theta). \]

差

\[ \boxed{ E(u_\theta)-E_N(u_\theta) } \tag{19} \]

はquadrature / sampling errorです.

したがって

\[ \boxed{ \text{small sampled loss} \not\Rightarrow \text{small continuous error} } \tag{20} \]

というSeason 3の基本問題がすでに現れます.

11.Deep Ritz errorには少なくとも三つの層がある

理想化すると, Deep Ritzの誤差要因は

\[ \boxed{ \text{representation} + \text{optimisation} + \text{quadrature / sampling} } \tag{21} \]

に分けて考える必要があります.

  • representation error:network familyがexact solutionをどこまで表現できるか,
  • optimisation error:parameter optimisationがglobal minimumへ届いたか,
  • quadrature error:sampled energyがcontinuous energyをどこまで再現するか,

です.

12.FEMのquadrature errorとの違いと共通点

FEMでもnumerical quadratureを使えばvariational crimeが起きます.

共通点は \[ \boxed{ \text{integralを有限個の点から近似する} } \tag{22} \] ことです.

違いは,Deep Ritzではintegrand自体がtraining中に \(\theta\) とともに変化することです. つまり固定されたpolynomialだけを積分しているわけではありません.

13.baseline problemを決める

exact solutionを

\[ \boxed{ u^\ast(x) = \sin(\pi x) } \tag{23} \]

とします. すると

\[ \boxed{ f(x) = \pi^2\sin(\pi x). } \tag{24} \]

exact energyは

\[ \boxed{ E(u^\ast) = -\frac{\pi^2}{4} = -2.4674011002723395\ldots } \tag{25} \]

です.

14.network architecture

今回はtanh network

\[ 1 \to 32 \to 32 \to 32 \to 1 \]

を使い, 最後に式 (14) のboundary factorを掛けます.

class Net(torch.nn.Module):
    def __init__(self, width=32, depth=3):
        super().__init__()

        layers = [
            torch.nn.Linear(1, width),
            torch.nn.Tanh()
        ]

        for _ in range(depth - 1):
            layers += [
                torch.nn.Linear(width, width),
                torch.nn.Tanh()
            ]

        layers += [torch.nn.Linear(width, 1)]
        self.net = torch.nn.Sequential(*layers)

    def forward(self, x):
        raw = self.net(x)
        return x * (1.0 - x) * raw

15.baselineでは64点Gauss–Legendre quadratureを使う

第1回ではpoint placementの比較をまだ行わず, かなり高精度なbaselineとして

\[ \boxed{ N=64 \text{ Gauss--Legendre points} } \tag{26} \]

を使います.

次回はnetwork,optimizer,point数を固定し, 点配置だけを変えます.

16.Gauss pointsとweightsを作る

import numpy as np
import torch
import math

torch.manual_seed(7)
torch.set_default_dtype(torch.float64)

Nq = 64

xi, wi = np.polynomial.legendre.leggauss(Nq)

# [-1, 1] -> [0, 1]
xq = (xi + 1.0) / 2.0
wq = wi / 2.0

xq = torch.tensor(xq[:, None])
wq = torch.tensor(wq[:, None])

17.energy lossを自動微分で作る

def energy(model, xq, wq):
    x = xq.clone().detach().requires_grad_(True)

    u = model(x)

    ux = torch.autograd.grad(
        u,
        x,
        grad_outputs=torch.ones_like(u),
        create_graph=True
    )[0]

    f = (
        math.pi ** 2
        * torch.sin(math.pi * x)
    ).detach()

    density = (
        0.5 * ux ** 2
        - f * u
    )

    return torch.sum(wq * density)

PINNsと違って二階微分 \(u_\theta''\) は使っていません. Poisson energyではfirst derivativeだけです.

18.optimiserもmethodの一部として分けて記録する

今回は

\[ \boxed{ 4000\text{ Adam steps} \quad+\quad \text{L-BFGS refinement} } \tag{27} \]

とします.

model = Net()

optimizer = torch.optim.Adam(
    model.parameters(),
    lr=1.0e-3
)

for epoch in range(4000):
    optimizer.zero_grad()

    loss = energy(model, xq, wq)
    loss.backward()
    optimizer.step()

lbfgs = torch.optim.LBFGS(
    model.parameters(),
    lr=1.0,
    max_iter=500,
    tolerance_grad=1.0e-12,
    tolerance_change=1.0e-14,
    line_search_fn="strong_wolfe"
)

def closure():
    lbfgs.zero_grad()
    loss = energy(model, xq, wq)
    loss.backward()
    return loss

lbfgs.step(closure)

19.baseline実行結果

double precision,seed 7で実行したbaselineでは

quantity value
sampled Deep Ritz energy\(-2.4674010603560346\)
exact energy\(-2.4674011002723395\)
\(L^2\) error\(9.34\times10^{-6}\)
\(H^1\) seminorm error\(2.83\times10^{-4}\)
max pointwise error\(1.70\times10^{-5}\)

これは「Deep Ritzは常にこの精度になる」という意味ではありません. 次回のpoint-placement comparisonのためのbaselineです.

20.energy identityを数値監査する

energy gapは

\[ E(u_\theta)-E(u^\ast) \approx 3.99163\times10^{-8}. \tag{28} \]

式 (8) から予測されるenergy errorは

\[ \boxed{ \sqrt{ 2\bigl(E(u_\theta)-E(u^\ast)\bigr) } \approx 2.82547\times10^{-4}. } \tag{29} \]

直接計算した \[ |u_\theta-u^\ast|_{H^1} \approx 2.82551\times10^{-4} \] と一致しています.

このtestは単にsolution plotを見るより強い数学的auditです.

21.なぜこの一致が重要なのか

Deep Ritz trainingではnetwork optimisationという複雑な処理をしています. しかし最後に

\[ \boxed{ 2(E(u_\theta)-E(u^\ast)) = |u_\theta-u^\ast|_{H^1}^2 } \tag{30} \]

というcontinuous identityへ戻せます.

つまり

\[ \boxed{ \text{neural computation} \longrightarrow \text{classical variational identity} \longrightarrow \text{audit} } \tag{31} \]

というSeason 3の基本方針が作れます.

22.ただしbaselineではquadrature errorを小さくしている

64-point Gauss–Legendreを使った理由は, まずsampling errorを十分小さくして network representationとoptimisationを観察するためです.

しかし実際のDeep Ritzでは

\[ \boxed{ \{x_i,w_i\}_{i=1}^N } \tag{32} \]

の選び方がtraining objectiveそのものを変えます.

23.同じ点数なら同じ情報量とは限らない

例えば \(N=32\) を固定しても

\[ \boxed{ \begin{aligned} &\text{equispaced},\\ &\text{random},\\ &\text{Gauss--Legendre},\\ &\text{Chebyshev-like},\\ &\text{boundary-clustered} \end{aligned} } \tag{33} \]

ではsampled energyが違います.

「network parameter数」だけをmodel complexityとして見るのではなく, where the PDE is observed も計算設計の一部です.

24.sampling measureとして見るとさらに分かりやすい

equal-weight samplingなら

\[ \mu_N = \frac1N \sum_{i=1}^N \delta_{x_i} \tag{34} \]

というempirical measureを使って \[ E_N \] を作っていると見なせます.

continuous energyはLebesgue measure \[ dx \] に対するintegralです.

したがってpoint placement problemは

\[ \boxed{ \mu_N \longrightarrow dx \quad\text{をどの意味で要求するか} } \tag{35} \]

という問題になります.

25.点が密なら十分,とは限らない

maximum gap \[ h_X = \max_i(x_{i+1}-x_i) \] が小さいことは重要なgeometry indicatorです. しかしhigher dimensionでは

\[ \boxed{ \text{fill distance}, \quad \text{separation distance}, \quad \text{discrepancy}, \quad \text{weights} } \tag{36} \]

など複数の量が現れます.

FEMでmesh qualityが一種類ではなかったのと同じです.

26.Deep RitzとPINNsでは点配置の意味が違う

Deep Ritzでは

\[ \boxed{ \text{points} \longrightarrow \text{energy quadrature} } \tag{37} \]

です.

PINNsでは

\[ \boxed{ \text{points} \longrightarrow \text{strong residual sampling}. } \tag{38} \]

operator learningではさらに

\[ \boxed{ \text{sensor points} \longrightarrow \text{input information itself}. } \tag{39} \]

Season 3ではこの三種類の「点」を区別します.

27.AIがDeep Ritzで間違えやすい点

mistake問題
sampled lossとcontinuous energyを同一視quadrature errorを消してしまう
neural trial familyをlinear spaceとして扱うGalerkin orthogonalityを誤用する
boundary penaltyとhard constraintを混同別のerror sourceを混ぜる
optimizer convergenceをfunction approximation convergenceと呼ぶoptimisation / representationを混同する
point数だけを記録して配置を記録しないexperimentが再現不能になる
一つのseedだけでmethod superiorityを主張stochastic variabilityを無視する

28.Deep Ritz implementation audit prompt

Audit prompt
このDeep Ritz implementationを数学的に監査してください.
(1) continuous PDEとenergy functionalがEuler–Lagrange equationで一致するか,
(2) Dirichlet boundary conditionをhard constraintかpenaltyか明示しているか,
(3) neural trial familyをlinear finite-element spaceと混同していないか,
(4) continuous energy \(E\) とsampled energy \(E_N\) を区別しているか,
(5) quadrature pointsとweightsを全て記録しているか,
(6) automatic differentiationで必要な微分次数が正しいか,
(7) representation・optimisation・quadrature errorを区別しているか,
(8) exact solutionがあるtestではenergy gap identityを確認しているか,
(9) optimizer・dtype・seedを記録しているか,
(10) training lossだけでsolution accuracyを判断していないか,
(11) point placementを固定せずmethod comparisonをしていないか,
(12) point-placement studyではnetwork・optimizer・point数を固定しているか
を順に確認してください.

29.第25回の結論

Deep Ritz法は,FEMと完全に別の世界ではありません. 出発点は同じRitz principleです.

\[ \boxed{ \text{Ritz FEM} : \min_{v_h\in V_h}E(v_h) } \tag{40} \]

を

\[ \boxed{ \text{Deep Ritz} : \min_{\theta\in\Theta}E_N(u_\theta) } \tag{41} \]

へ置き換えています.

しかしこの一文字の違い

\[ \boxed{ E \quad\longrightarrow\quad E_N } \tag{42} \]

にpoint placementの問題が入っています.

Season 3ではここを中心に,

\[ \boxed{ \text{mesh geometry} \longrightarrow \text{sampling geometry} } \tag{43} \]

という対応を追います.

Season 3 第1回の原則
Deep Ritzではnetwork architectureだけでなく, energyをどの点で観測したかまでmethodの一部である.

次回はnetwork,optimizer,point数を固定して, 第26回:Deep Ritzでは点をどこに置くか — quadratureとsampling geometry へ進みます.

参考文献・関連ページ

  1. W. E and B. Yu, “The Deep Ritz Method: A Deep Learning-Based Numerical Algorithm for Solving Variational Problems”, Communications in Mathematics and Statistics 6 (2018), 1–12.
  2. P. G. Ciarlet, The Finite Element Method for Elliptic Problems, North-Holland, 1978.
  3. S. C. Brenner and L. R. Scott, The Mathematical Theory of Finite Element Methods, 3rd ed., Springer, 2008.
  4. 第24回:AI時代に有限要素法をどう設計・検証するか — 数学構造からmethodを選ぶ
  5. 関連する先行ノート:1次元Poisson問題でPINNsを動かす
  6. 関連する先行ノート:残差点の配置を変えると何が起きるか
  7. 関連する先行ノート:PINNs / Deep Ritz / VPINN / WANを並べて比べる

ページの先頭へ